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

byte, c, cpu-word

Solution

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).

Problem

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?

Original source

Related problems