Results 1 to 2 of 2

Thread: Having trouble switching endians

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Mar 2013
    Posts
    21

    Having trouble switching endians

    I am trying to learn some basics in how to read and write lseek functions. I am having an issue with endians. I found a source code that is supposed to work, however it is reading everything backwards for me. This is my code:

    Code:
    Code:
    for(i = 0;i < 7;i++)
    		{
    		lseek(handle,1200 + i * 60,SEEK_SET);
    		read(handle,&(member[i].name),12);
    		read(handle,&(member[i].age),2);
    .
    The only problem is that for the name and some other variables it is reading it as nalyeK instead of Keylan. It is also throwing off some of my numbers. I am trying to get House numbers, and instead 2046 (07FE) it is giving me 65031 (FE07). I know it is an endian issue, as I have had this kind of thing happen in vb. I am not sure how to fix it in C++.

    I have found a lot of different things on Google regarding swapping bytes and switching endians, but most of these codes are many lines long (8 for the shortest, and almost 20 for the longer ones). I am not sure how to implement them. If I need to do this every time I need to switch, or if it will permanently switch it in the program.

    Does anyone have any ideas? I can provide more of the code if need be.

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Having trouble switching endians

    To swap endianness, you need to "mirror" the bytes in the value. For instance, to swap the endianness of a 32-bit integer, you'd do something like this:

    Code:
    int32_t swap(int32_t in)
    {
        return ((in & 0x0000FF00) << 8) | ((in & 0x00FF0000) >> 8) |
        			((in & 0x000000FF) << 24) | ((in & 0xFF000000) >> 24);
    }
    If you can read and understand this piece of code, you should be able to implement functions for swapping endianness of other sized integers (16 bit, 64 bit, etc) aswell.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width