How to extract 2 bytes from a word, and how to make a word from 2 bytes (in C)?

18,485

Solution 1

You're not shifting when you split the word. So if grpix is 0x1234, then grpixl gets the expected 0x34 but grpixh ends up as 0x1200. You should say

byte grpixh = grpix >> 8;

Of course, you're also ignoring any endianness concerns that may be present. You should probably convert your word to a known endian (with something like htons()) before attempting to split (and do the reverse conversion when joining).

Solution 2

Get to know: http://graphics.stanford.edu/~seander/bithacks.html for doing all manner of operations.

right_byte = short_val & 0xFF;
left_byte = ( short_val >> 8 ) & 0xFF

short_val = ( ( left_byte & 0xFF ) << 8 ) | ( right_byte & 0xFF );

I always do a &0xFF mask to assure I have no sign problems.

Share:
18,485
Fernando Aires Castello
Author by

Fernando Aires Castello

I'm a Java software developer from Florianópolis, SC (Brazil). I can speak Portuguese (natively), English, basic Romanian and basic modern Greek. I am able to program in C/C++, C#, Java, Javascript, Delphi, BASIC and Assembly (especially for Z80 and x86 architectures).

Updated on June 05, 2022

Comments

  • Fernando Aires Castello
    Fernando Aires Castello about 2 years

    I am trying to extract two bytes from a 16-bit word, and to make a 16-bit word from two bytes. This is what I have tried (byte = unsigned char, word = unsigned short):

    Split grpix word into 2 bytes:

    word grpix; // Assume that the value has been initialized
    
    byte grpixl = grpix & 0x00FF;
    byte grpixh = grpix & 0xFF00;
    

    Make grpix word from 2 bytes

    byte grpixh; // Assume that the value has been initialized
    byte grpixl; // Assume that the value has been initialized
    
    word grpix = grpixh;
    grpix <<= 8;
    grpix += grpixl;
    

    For some reason, my code doesn't work as expected, and now I'm not sure if the "splitting" of the word is wrong, if the "making" of the word is wrong, or both... Could you give me some advice?

  • Lily Ballard
    Lily Ballard over 11 years
    In a 16-bit word, the mask here is pointless, because the bottom 8 bits will be discarded by the shift already.
  • Fernando Aires Castello
    Fernando Aires Castello over 11 years
    I changed my code to this: byte grpixh = (grpix >> 8) & 0x00FF; and now it works :)