0

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?

3
  • Very similar to this link. Commented Feb 5, 2017 at 12:40
  • Cast to unsigned char for safety. An unsigned char is a small integer in the range 0-0xFF. Two of them can be combined to mkae a 16-bit integer in the range 0-0xFFFF simply by bit shifting and logical or-ing Commented Feb 5, 2017 at 12:54
  • @MalcolmMcLean: to accomodate 16-bit ints, it would be safer to cast the result to (unsigned int) before shifting. The specific values in the example would not pose a problem, but the code should be as generic and portable as possible. Commented Feb 5, 2017 at 12:57

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks all for the help, I have edited the original post to make the question clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.