Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the output look like this?

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!

like image 871
pythoniku Avatar asked Oct 17 '12 22:10

pythoniku


2 Answers

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.

like image 76
pro_metedor Avatar answered Nov 04 '22 10:11

pro_metedor


Your system stores numbers as Little Endians

like image 28
StoryTeller - Unslander Monica Avatar answered Nov 04 '22 11:11

StoryTeller - Unslander Monica