1

I would like to assign hex values into char type. Due to null (\x00) character, I cannot assign all hex values. Just 4 character can be assigned. How to assign all hex values in (char*)data ??

unsigned char data[100];
sprintf((char*)data,"\x30\x29\x02\x01\x00\x04\x06\x70\x75\x62\x6c\x69\x63\xa0");
coder
  • 12,832
  • 5
  • 39
  • 53

2 Answers2

2

Since you have all your hex numbers available at compile time, you can assign them using curly brace initializer instead of a string literal:

unsigned char data[] = {
    0x30, 0x29 ,0x02, 0x01, 0x00, 0x04, 0x06,
    0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa0
};
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

In C, code cannot assign multiple values of an array with one assignment. Code can initialize as is this good answer.

Use a loop or memcpy() to assign multiple values.

unsigned char data[100];
#define SOURCE_DATA ("\x30\x29\x02\x01\x00\x04\x06\x70\x75\x62\x6c\x69\x63\xa0")
#define SOURCE_SIZE (sizeof SOURCE_DATA - 1)
memcpy(data, SOURCE_DATA, SOURCE_SIZE);
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256