Nicolas
Nicolas

Reputation: 63

C Write Bit in Memory

If I have an 8 bit number like so, 00101001,

Currently in my code I have two functions as shown:

void ADDSET(unsigned char *signalmask, int SIGNUM) {
    *signalmask = *signalmask | (SIGNUM);
}

void DELSET(unsigned char *signalmask, int SIGNUM) {
    *signalmask = *signalmask &~ SIGNUM;
}

With a function call like so:

int main() {
    unsigned char signalmask = 41;
    int SIGNUM = 7; // signal 1-8

    ADDSET(&signalmask, SIGNUM);

    return 0;
}

For some reason when I output my signalmask's memory address it either doesn't replace/remove the bit, or it does the wrong one. I think this is because the SIGNUM is starting at 0 when it should be starting at 1.

I output using:

for (i = 0; i < 8; i++) {
    printf("%d", !!((signalmask << i) & 0x80));
}

Can anybody help me?

Note: My INSET function works as desired:

int INSET(unsigned char signalmask, int SIGNUM){
    unsigned char bitMask = 1 << (SIGNUM - 1);
    if ((signalmask & bitMask) == 0)
        return 0;
    else
        return 1;
}

My problem is I don't know how to port this code over to the ADDSET and DELSET functions.

Thanks in advance.

Upvotes: 2

Views: 342

Answers (2)

user3629249
user3629249

Reputation: 16540

Given the description of the signum (=7) the code should look similar to :

void addSet(unsigned char *signalMask, int sigNum) 
{ // turn bit ON
    *signalMask = *signalMask | (1<<sigNum);
} // end function: addSet

void selSet(unsigned char *signalMask, int sigNum) 
{ // turn bit OFF
    *signalMask = *signalMask & ~(1<<sigNum);
}

I would also check that signum was in the range (0...31)

General practice is only macro names and constants are all CAPS.

  • Using 'camel case' for function names and parameter names is expected and very readable (although separating individual words with an '_' is acceptable)

  • Using all lower case for names makes reading/understanding the code more difficult

Upvotes: 3

David C. Rankin
David C. Rankin

Reputation: 84521

An equivalent, but slightly more compact syntax is:

void ADDSET(unsigned char *signalmask, int SIGNUM) {
    *signalmask |= (1 << SIGNUM);
}

void DELSET(unsigned char *signalmask, int SIGNUM) {
    *signalmask &= ~(1 << SIGNUM);
}

If you simply want to toggle whatever is there (i.e. 1->0 or 0->1):

void TOGGLESET(unsigned char *signalmask, int SIGNUM) {
    *signalmask ^= (1 << SIGNUM);
}

Upvotes: 3

Related Questions