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) and htons
(host-to-network-short) translating functions. After you receive, you need to use ntohl
and ntohs
functions 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 use char
type for this kind of raw bytes manipulations.
Your system stores numbers as Little Endians
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With