convert int to char array Big Endian

放肆的年华 提交于 2019-12-02 09:04:08

Whatever is the endianness of your system, your SerializeInt function will store value in big endian in the array buffer. It is stored as big endian as it writes the most significant byte first. Remember that when you evaluate value it has no endianness per se, it's like any mathematical value.

The code will always write the integer in char array in big-endian way. This is because you are always saving MSB at buffer[0] and LSB at buffer[3].

Suppose in a little endian machine:

you have number 0x11223344: (in hexadecimal format)

Address      ->      2003  2002  2001  2000

`int` Number ->       11    22    33    44
Buffer       ->   index[3]  [2]   [1]   [0]

The same representation on a big endian machine will be:

Address      ->      2000  2001  2002  2003  <= See only the addressing changed/reversed

`int` Number ->       11    22    33    44
Buffer       ->   index[3]  [2]   [1]   [0]

In both machines, integer << 24 will mean MSB and (int8_t)integer will mean LSB.

Big-Endian is defined as with the big end (i.e. most significant bit/byte) first. So, yes, the function writes the value in big-endian format to the buffer.

However, returning a pointer one past the buffer strikes me as unusual.

Apart from the already posted answers regarding endianess...

Does this function work correctly on both Little endian and Big endian machines?

No, because you use bit-wise arithmetic on the default int type. If the int is negative, the behavior is implementation-defined. In general, it doesn't make any sense whatsoever to use bit-wise operators on signed integers.

Furthermore, your code relies on int being 32 bits, of which there are no guarantees.

So your code is completely non-portable. Fix it in the following way:

#include <stdint.h>

uint8_t* SerializeInt (uint8_t* buffer, uint32_t value)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!