Akhil Akhil - 4 years ago 187
C Question

Convert char array to hex array

Input:

char arr1[9] = "+100-200" // (+ is 2B, - is 2D, 1 is 31 and 2 is 32)


Output:

unsigned int arr2[4]= [0x2B31,0x3030,0x2D32,0x3030]


How can I do this?

Answer Source

Your question seems inconsistent: 0 should convert to 0x30, its ASCII value.

Why this modification, the code is quite straightforward:

char arr1[8] = "+100-200";
unsigned int arr2[4];

for (int i = 0; i < 8; i += 2) {
    arr2[i / 2] = ((unsigned int)(unsigned char)arr1[i] << 8) |
                   (unsigned int)(unsigned char)arr1[i + 1];
}

for (int i = 0; i < 4; i++) {
    printf("0x%04X ", arr2[i]);
}
printf("\n");

Output:

0x2B31 0x3030 0x2D32 0x3030
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download