1

How to convert the list of the 16bit numbers to the hexadecimal string like "\x0f\x56\x44\xe0".

How do these 16 bit values look? They are the result of the macro expansion too #define make_word(arg1, arg2) arg1 << 16 + arg2. So the full call should look like: some_function(MAKE_HEX_STR(make_word(1, 2), make_word(3, 4), make_word(5, 6)); and should expands to the: some_function("\x01\x02\x03\x04\x05\x06);

Charles Ofria
  • 1,936
  • 12
  • 24
Anton Kochkov
  • 1,117
  • 1
  • 9
  • 25
  • why don't you just use `strtoul()` to convert the string to an integer? – The Paramagnetic Croissant Sep 24 '15 at 07:38
  • Why cannot you just cast your `unsigned short` array to `unsigned char`, and use that? It's unclear what you are trying to do. – user694733 Sep 24 '15 at 08:49
  • 1
    Note: `"\x01" "\x02" "\x03" "\x04" "\x05" "\x06"` is the same as `"\x01\x02" "\x03\x04" "\x05\x06"` and `"\x01\x02\x03\x04\x05\x06"`. So the problem is now only how to make `1` --> `"\x01"`, `255` --> `"\xFF"` in the pre-processor, – chux - Reinstate Monica Sep 24 '15 at 13:39
  • @AntonKochkov: The preprocessor won't evaluate `arg1 << 16 + arg2` so if you really want to do this in the preprocessor you'll need to use BOOSTPP. (And, by the way, `arg1<<16 + arg2` won't fit in 16 bits unless `arg1` is 0. Maybe you meant the shift to be 8 bits.) But you'd probably be better off using string concatenation instead of arithmetic, as @chux suggests. – rici Sep 24 '15 at 16:55
  • @rici yes, you right, this was a typo, of course I mean shift by 8 bits, but probably it isn't needed in case of the string concatenation. – Anton Kochkov Sep 24 '15 at 17:05

2 Answers2

1

I don't know what task is behind your question, but it's possible that the following will help (requires C99 or more recent):

#define MAKE_WORD(x,y) x,y
#define MAKE_STR(...) ((char[]){__VA_ARGS__, 0})

See it live on ideone. If you don't really need it to be a string, you could leave out the 0 terminator.

rici
  • 234,347
  • 28
  • 237
  • 341
0

You can try to use strtol and specify the base as 16.

or you can try like this:

int x = yourNumber;
char result[5]; 
if (x <= 0xFFFF)
{
    sprintf(&result[0], "%04x", x);
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331