I have a c program below, I would like to send out a 32 bit message in a particular order Eg.0x00000001.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <stdint.h>
struct test
{
uint16_t a;
uint16_t b;
};
int main(int argc, char const *argv[])
{
char buf[4];
struct test* ptr=(struct test*)buf;
ptr->a=0x0000;
ptr->b=0x0001;
printf("%x %x\n",buf[0],buf[1]); //output is 0 0
printf("%x %x\n",buf[2],buf[3]); //output is 1 0
return 0;
}
Then I test it by print out the values in char array. I got output in the above comments. Shouldn’t the output be 0 0 and 0 1? since but[3] is the last byte? Is there anything I missed?
Thanks!
Cause its little endian. Read this:
Endianness
For translating them into network order, you have to use
htonl(host-to-network-long) andhtons(host-to-network-short) translating functions. After you receive, you need to usentohlandntohsfunctions to convert from network to host order. The order which your bytes are placed in the array depends on the way how did you put them in memory. If you put them as four separate short bytes, you will omit endianness conversion. You may usechartype for this kind of raw bytes manipulations.