A89: Filling a Byte in C


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

A89: Filling a Byte in C




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:

byte GetByteMask(char Start, char End)
{
 TBitMaskByte Res;
 memset (&Res, 0x00, 1);
 if ((Start <= 0) && (End >= 0))
  Res.Bit0 = BitOn;
 if ((Start <= 1) && (End >= 1))
  Res.Bit1 = BitOn;
 if ((Start <= 2) && (End >= 2))
  Res.Bit2 = BitOn;
 if ((Start <= 3) && (End >= 3))
  Res.Bit3 = BitOn;
 if ((Start <= 4) && (End >= 4))
  Res.Bit4 = BitOn;
 if ((Start <= 5) && (End >= 5))
  Res.Bit5 = BitOn;
 if ((Start <= 6) && (End >= 6))
  Res.Bit6 = BitOn;
 if ((Start <= 7) && (End >= 7))
  Res.Bit7 = BitOn;
 return *((byte*)(&Res));
}

where TBitMaskByte is a bitfield declared as:

typedef struct
{
 unsigned char Bit7: 1;
 unsigned char Bit6: 1;
 unsigned char Bit5: 1;
 unsigned char Bit4: 1;
 unsigned char Bit3: 1;
 unsigned char Bit2: 1;
 unsigned char Bit1: 1;
 unsigned char Bit0: 1;
} TBitMaskByte;

and byte is an unsigned char.


Well, any solutions?  Remember that you can write code segments in ASM, but
personally I don't know how to handle local variables and parameters.

Thanks for your help,

Sebastian Reichelt




Follow-Ups: