0

I want to set an N amount of bits in a byte (byte always starts as 0) and store it using a pointer. Imagine:

void SetBits(uint8_t bytesToSet, uint8_t* var) {}

How would I go about implementing this (using C)?

kiryakov
  • 145
  • 1
  • 7

1 Answers1

2

Where should that N bits be set? To the left, to the right?

If you want to have those N bits to the right, your function should look like this:

void SetBits(uint8_t bitsToSet, uint8_t* var)
{
    if (bitsToSet < 8)
        *var = (1 << bitsToSet) - 1;
    else {*var = 0; *var = ~(*var);}
}

For an example, for the call SetBits(5,&a), variable a will hold the value 0b00011111.

Tudor
  • 436
  • 3
  • 10