1

I have a struct that is defined as:

struct record
{
   int age;
   char name[12];
   int department;
};

I am confused on how to approach this problem if im reading data from a binary file and the data contains structs how can I reverse the order of the bits from big endian to little endian in that struct?

user2671024
  • 75
  • 1
  • 8
  • 6
    What about [`ntohs`](http://linux.die.net/man/3/ntohs) and friends? – Michael Foukarakis Feb 11 '14 at 21:58
  • Is there anyway to do this without library functions? – user2671024 Feb 11 '14 at 21:59
  • 3
    @user2671024 Sure, but you would end up duplicating the functions almost word for word. Whats the point? – Sinkingpoint Feb 11 '14 at 22:00
  • 4
    Converting between big endian and little endian pertains to byte ordering, not bit ordering. Within each byte the bit ordering is not changed. – Gavin H Feb 11 '14 at 22:00
  • 1
    Note that you just need to byte swap `age` and `department` - `name` will not be affected by endianness – Paul R Feb 11 '14 at 22:01
  • 5
    Note the machines might have different sizes for integers as well, and the compilers might add a different amount of padding to the structures, so endianness might not be your only problem. – Guntram Blohm Feb 11 '14 at 22:01
  • you should read this http://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine – 0x90 Feb 11 '14 at 23:31
  • it effects byte ordering not bit ordering so here there is no problem if you are using the same structure in little and big endian machine .better to use "packet" attribute to make of fix pack of struct – user2760375 Feb 12 '14 at 03:00

1 Answers1

0

Here is a simple implementation to convert endianness:

// Convert from big to little or vice versa
void convert_record (struct record *bigLittle) {
    int x, temp;

    temp = bigLittle->age;

    for (x = 0; x < sizeof (int); x++) {
        ((char *)&(bigLittle->age))[x] = ((char *)&temp)[sizeof (int) - x]
    }

    temp = bigLittle->department;

    for (x = 0; x < sizeof (int); x++) {
        ((char *)&(bigLittle->department))[x] = ((char *)&temp)[sizeof (int) - x]
    }

    return;
}

However, as Michael Foukarakis has pointed out above, you really ought to use ntohs and friends.

haneefmubarak
  • 1,911
  • 1
  • 21
  • 32