C and endians

This is a discussion on C and endians within the C Programming forums, part of the General Programming Boards category; I have a question regarding endians. I have this piece of code that I'm compiling on a Pentium 4 machine, ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    2

    C and endians

    I have a question regarding endians.
    I have this piece of code that I'm compiling on a Pentium 4 machine, and it doesn't behave like I expect it to.

    Code:
    void CREARECOMANDA(char adresaSlave, char tipComanda, unsigned short adresaRegistru, unsigned short numarCuvinte){
    	unsigned short crc;
    	comanda[0]=adresaSlave;
    	comanda[1]=tipComanda;
    	comanda[2]=adresaRegistru>>8;
    	comanda[3]=adresaRegistru;
    	comanda[4]=numarCuvinte>>8;
    	comanda[5]=numarCuvinte;
    	crc=CRC16(comanda,6);
    	comanda[6]=crc;
    	comanda[7]=crc>>8;
    }
    "comanda" is an array of unsigned char. The thing is, from what I've read on the internet, Intel processors use Little-Endian encoding. So placeing foo=0x0A0B into 2 one byte numbers would be
    Code:
    bar[0]=foo&255;
    bar[1]=(foo>>8)&255;
    But the code i just wrote does this the other way arround. The funny thing is it does'n do so for al the numbers. "crc" is of type usigned short, and "CRC16" returns unsigned short, yet the separation of bytes doesn't work like it did for the unsigned shorts before that. I can't figure out why the code behaves like it does. What am I missing?

    P.S. I'm using LabWindows/CVI as IDE.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,848
    I think you might be over-analysing the problem.

    comanda[2]=adresaRegistru>>8;
    comanda[3]=adresaRegistru;
    This writes MSB, then LSB

    comanda[6]=crc;
    comanda[7]=crc>>8;
    This writes LSB, then MSB

    Done consistently, this approach is independent of the host endian-ess.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    2
    Quote Originally Posted by Salem View Post
    I think you might be over-analysing the problem.
    Solved. Turns out I wasn't analyzing enough. It was a silly miscalculation. Thanks.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21