Re: Convert 00010000 to 11110000......how?
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Thu, 31 Aug 2006 15:28:04 -0400
farnaz.shahed@xxxxxxxxx wrote On 08/31/06 15:03,:
Hi,
This what I'm basically supposed to do. If i have a byte which looks
like this 00010000, i need to convert it to 11110000. That would mean
if any of the bit fields is 1....all the bit fields to the left of it
should be made 1.
Assuming an eight-bit byte:
unsigned char byte = ...;
byte |= (byte << 1) | (byte << 2) | (byte << 3)
| (byte << 4) | (byte << 5) | (byte << 6)
| (byte << 7);
Generalizing to bytes of arbitrary width:
#include <limits.h>
...
unsigned char byte = ...;
int s;
for (s = 1; s < CHAR_BIT; ++s)
byte |= byte << s;
Sneakier method:
unsigned char byte = ...;
if (byte > 0) /* delete if 00...0 should give 11...1 */
byte = ~(((byte & (byte - 1u)) ^ byte) - 1u);
--
Eric.Sosman@xxxxxxx
.
- References:
- Convert 00010000 to 11110000......how?
- From: farnaz . shahed
- Convert 00010000 to 11110000......how?
- Prev by Date: Re: Convert 00010000 to 11110000......how?
- Next by Date: Re: Convert 00010000 to 11110000......how?
- Previous by thread: Re: Convert 00010000 to 11110000......how?
- Next by thread: Re: Convert 00010000 to 11110000......how?
- Index(es):
Relevant Pages
|