0

I have array of chars:

char macChars=[12];

The content of it is e.g. macChars[0]=53, macChars[1]=66 ... I need to convert these numbers to hex chars, so i would have another array:

 macCharsHex[0]=5 //value 53 in hex
 macCharsHex[1]=B //value 66 in hex

Thank you.

1
  • I'm having a hard time understanding your question. "convert to hex chars" doesn't mean much. Do you mean arr[0] = 'B';? Commented Jan 27, 2012 at 11:32

4 Answers 4

1

Assuming ASCII, your example already does contain the values you want them to contain. So you don't have to convert anything. Maybe you want to print them?

Sign up to request clarification or add additional context in comments.

2 Comments

My bad, terrible choice of question title.
But it's still not clear what you want. If macChars[1]==66, what does macCharsHex[1] need to become?
1

This should work:

    char hex[255] = {0};       // Varible to hold the hex value
    int dec = 1234;            // Decimal number to be converted
    sprintf(hex,"%X", dec);
    printf("%s", hex);         // Print hex value

Comments

1

Use sprintf(), for instance. Note that it will take more space, if you have 12 bytes you will need 24 + 1 bytes for the string representation, since each byte requires two characters in hex and then the terminating '\0'-byte.

I suspect that I don't understand the question at all, especially not the example given.

If you have macChars[0] == 53, which is 0x35 in hex, then I would expect to get maxCharsHex[0] == '3' and macCharsHex[1] == '5' after the first char has been converted. This is done like so with sprintf():

sprintf(maxCharsHex, "%02x", (int) macChars[0] & 0xff);

The cast and mask is to be on the safe side for signed characters.

1 Comment

Will not it do the reverse convert?
0

They are already converted, since character in C are represented by their corresponding character codes.

Therefore, as far as storing things in arrays is concerned there is nothing you need to do and if you want "5" and "B" to show up correctly when printing or doing something like that its a matter of using the correct printing function (putchar, printf with %c, etc).

Comments

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.