Re: A89: Filling a Byte in C


[Prev][Next][Index][Thread]

Re: A89: Filling a Byte in C






On Sun, 14 May 2000, Sebastian Reichelt wrote:

> 
> Hi,
> 
> does anyone know how to fill a byte from bit x to bit y with ones in C, and
> fill the rest with zeros.  Here's my solution, but I'm sure there is a much
> better way:

I'm not sure if this way is better, but it is certainly smaller:

char GetByteMask(char start, char end)
{
    char x = 0;
    int y;
    for (y = start; y <= end; y++)
        x |= 1 << y;
    return x;
}

In case you can't guess:

x |= y      means set X to X logical or Y
x << y      means shift x left y bits (multiply x by 2^y)




Follow-Ups: References: