Something closed, but I can not google. There is a hexadecimal number, for example, 0x046A. How to convert it to an array 0x00, 0x04, 0x06, 0x0A? C ++ language.

I beg your pardon. Along the way, I was wrong. Need a string like "046A"

  • In the cycle, we put in the element of the array X & 0x0F , then X=X>>4 and so on until X is 0. Most likely, we should write the array backwards - Mike
  • Is it possible to more accurately formulate the question? There is a hexadecimal number - and where is it? In a variable or in a file? What type of variable? Next: what exactly to get? The string char [], broken by how many digits? If there is no clear statement, there will be no right answer, because the decision depends on these questions completely. - Zealint
  • There is an int 0x046A. It needs to be converted to the string "046A" for subsequent sending to the port - Hermann Zheboldov

2 answers 2

printf ("% 04X", 0x046A); gives the output just "046A".

  • So much extra here with you. printf("046A"); - αλεχολυτ

The honest option:

 unsigned short int x = 0x046A; unsigned char b[4]; b[0] = x&0x0F; b[1] = (x >> 4)&0x0F; b[2] = (x >> 8)&0x0F; b[3] = (x >> 12)&0x0F; 

To a certain extent, the hack:

 union { unsigned short int x; struct { unsigned char b0: 4; unsigned char b1: 4; unsigned char b2: 4; unsigned char b3: 4; }; } data; data.x = 0x046A; printf("%02X %02X %02X %02X\n",data.b0,data.b1,data.b2,data.b3); 

Update Once you need a string, then on pure :) C ++, you can do this:

 ostringstream s; s << hex << setw(4) << setfill('0') << x; cout << s.str() << endl; 

or simply

 char buffer[5]; sprintf(buffer,"%04hX",x); 
  • I was wrong. need the string "046A" - Hermann Zheboldov
  • @HermannZheboldov The easiest way is sprintf(buffer,"%04X",x) :) More difficult, but pure C ++ - ostringstream s; s << hex << setw(4) << setfill('0') << x; cout << s.str() << endl; ostringstream s; s << hex << setw(4) << setfill('0') << x; cout << s.str() << endl; - Harry
  • Well, the union option is like UB, no? Honest option is more honest somehow. (Although the question arises, how do you get binary data in the bit field so that the standard is satisfied. memcpy ?) - VladD
  • somewhere we have already discussed this question) only there was a direct caste of the pointer ... The standard allows to char - like anything to cast. - pavel
  • @VladD Frankly, I don’t know, so I wrote that the hack ... - Harry