Re: Convert 00010000 to 11110000......how?





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

.



Relevant Pages