There is an array with 4 bytes, how will they be placed in uint32?

uint8 arr[4] = {0xDD, 0xFF, 0xCC, 0xBB}; uint32 ret = ...; 

And conduct the reverse operation:

 uint32 i = 0xDDFFCCBB; uint8 arr[4] = ...; 

2 answers 2

If you both had one order of bytes, there would be no problems:

 uint8 arr[4] = {0xDD, 0xFF, 0xCC, 0xBB}; uint32 ret = *(uint32*)arr; 

In your version you have to

 ret = arr[3]|(arr[2] << 8)|(arr[1] << 16)|(arr[0] << 24); 

Back - about the same:

 arr[3] = ret&0xFF; arr[2] = (ret >> 8)&0xFF; arr[1] = (ret >> 16)&0xFF; arr[0] = (ret >> 24)&0xFF; 

    There is another way - the use of associations. The order of the bytes in this case does not matter. Combinations in C are similar to structures with the only difference that each element of the union is located at the same memory address. In your case it will look like this:

     typedef union { uint32 word, uint8 bytes[sizeof(uint32)] } WordChar; 

    In the future, you can use the WordChar type as follows:

     WordChar wc; wc.bytes[0] = 0xDD; wc.bytes[1] = 0xFF; wc.bytes[2] = 0xCC; wc.bytes[3] = 0xBB; uint32 ret = wc.word; //0xDDFFCCBB 

    The same applies to the type of float : you can break it into bytes in the same way. Here is my article, where everything is described in detail .

    • Everything is very bad with your decision. It violates strict-aliasing and is suitable for the surprise of colleagues with the words "look, an error in the compiler !!!! 11" The fact is that C prohibits writing in some fields of the union, and reading from others. stackoverflow.com/questions/2906365/… - gbg
    • @gbg, if it is impossible to write in some fields, and read from others, then why was the union introduced at all? - maestro
    • In addition, if it were a float, then Harry’s solution would no longer work. Only associations. - maestro
    • @gdb According to your link, Abyx writes that char and uchar is a special case. Who is right? - Cerbo