Search code examples
cintbytebitshort

How to work with left and right bytes of a short int?


I have a short int, which is 2 bytes, but I only want to output the left byte to a file. How do I do this? I'm using binary functions open(), read(), write(), etc.

I would also like to shift the right byte to the left 8 times, so that the right byte occupies the left, and the right has been cleared to all 0's.

I apologize for not showing what I've already tried -- I'm a C noobie and cannot find anything about how to do this.


Solution

  • You could try this approach

        int someNum = 0x1234;
        int  leftByte, rightByte;
    
        leftByte = (someNum >> 8) & 0xff;
        rightByte = (someNum) & 0xff;