Re: What's wrong with this code?



On 2007-09-30 12:40, Army1987 <army1987@xxxxxxxxx> wrote:
On Sat, 29 Sep 2007 08:43:44 -0700, xbyte wrote:
It's a problem from a book, and I can't figure it out.

4 words (4x8 bits) are packed into a 32-bit unsigned integer, and
you've gotta extract an indicated (by bytenum) word from it, AND the
following code is said to be written by a failed programmer:

int xbyte(unsigned word, int bytenum)
{
return (word >> (bytenum << 3)) & 0xFF;
}

IMHO, this is a perfect bulk of code, what's your opinion?
None. But if you replace `<< 3` with `* CHAR_BIT` and 0xFF with
UCHAR_MAX (these are in <limits.h>), you don't have to know how
big the word and the bytes are.

Except that the requirement explicitely says "4x8 bits", not 4 x
CHAR_BIT bits. That may be an error in the requirement, but more likely
it is mandated by some external source, like a file format or a
communication protocol (in the real world - I have seen that this
problem is from "a book"). Then * 8 and & 0xFF will work correctly even
on machines with larger bytes, but * CHAR_BIT and UCHAR_MAX will not.

hp

--
_ | Peter J. Holzer | I know I'd be respectful of a pirate
|_|_) | Sysadmin WSR | with an emu on his shoulder.
| | | hjp@xxxxxx |
__/ | http://www.hjp.at/ | -- Sam in "Freefall"
.



Relevant Pages

  • Whats wrong with this code?
    ... words are packed into a 32-bit unsigned integer, ... you've gotta extract an indicated word from it, ... int xbyte(unsigned word, int bytenum) ... IMHO, this is a perfect bulk of code, what's your opinion? ...
    (comp.lang.c)
  • Re: Whats wrong with this code?
    ... words are packed into a 32-bit unsigned integer, ... you've gotta extract an indicated (by bytenum) word from it, ... int xbyte ...
    (comp.lang.c)
  • Re: Whats wrong with this code?
    ... words are packed into a 32-bit unsigned integer, ... you've gotta extract an indicated (by bytenum) word from it, ... int xbyte ... The programmer might have failed the course, but the code is good enough to be used even in a production environment. ...
    (comp.lang.c)
  • Re: Whats wrong with this code?
    ... words are packed into a 32-bit unsigned integer, ... you've gotta extract an indicated (by bytenum) word from it, ... int xbyte ... undefined behaviour awaits if bytenum is out of range. ...
    (comp.lang.c)
  • Re: Whats wrong with this code?
    ... you've gotta extract an indicated (by bytenum) word from it, ... int xbyte(unsigned word, int bytenum) ... a hamburger is better than eternal happiness. ...
    (comp.lang.c)