Re: What's wrong with this code?
- From: "Peter J. Holzer" <hjp-usenet2@xxxxxx>
- Date: Sun, 30 Sep 2007 19:33:13 +0200
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.None. But if you replace `<< 3` with `* CHAR_BIT` and 0xFF with
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?
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"
.
- References:
- What's wrong with this code?
- From: xbyte
- Re: What's wrong with this code?
- From: Army1987
- What's wrong with this code?
- Prev by Date: Re: Should we broaden the topicality of this group?
- Next by Date: Re: Should we broaden the topicality of this group?
- Previous by thread: Re: What's wrong with this code?
- Next by thread: Solutions to "C Programing Language"
- Index(es):
Relevant Pages
|