c - Integer to byte array Little Endian and vice versa -


i want methods convert integer byte array (little endian), , byte array (encoded in little endian way) integer in c; regardless if work on le or machine.

are these functions fine this?

void int2bytearrayle(int x,unsigned char *bytearray) {    bytearray[0]=x;   bytearray[1]=x>>8;   bytearray[2]=x>>16;   bytearray[3]=x>>24; }   void bytearrayle2int(unsigned char *bytearray, int*x) {   *x=bytearray[0] | (bytearray[1]<<8) | (bytearray[2]<<16) | (bytearray[3]<<24); } 

ps. work if x signed?

what trying convert between host byte order , network byte order. , need functions htonl , ntohl.

to convert host network byte order use:

uint32_t n = (uint32_t)htonl((uint32_t)h); 

and in opposite direction:

int h = (int)ntohl((uint32_t)n); 

these functions aware of endianness of host platform. if execute code on big endian machine, these functions nothing. on little endian machine functions reverse bytes.

in comments intimate communication protocol requires information passed in little endian byte order. surely mistake. should follow standard protocol , transmit data on wire in network byte order.

if cannot change protocol, , expects little endian on wire, need memcpy. values little endian , reversing bytes won't help.

if find on big endian client of course need reverse bytes. use function that:

uint32_t reversebytes32(uint32_t v){   return ((v & 0xff) << 24) | ((v & 0xff00) << 8)           | ((v & 0xff0000) >> 8) | ((v & 0xff000000) >> 24); } 

you'll need use casts reinterpret signed int unsigned uint32_t.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -