Teuntje Teuntje - 1 month ago 9
C Question

Flipping certain bit in an integer (C language)

I'm trying to get my program to work where a certain bit is being flipped. I have this function called

flipbit(int *p, int m)
. The user needs to input a digit and a bit number. Let's say the user gives the number
8
(
00001000
) and the bit number
2
, so the 2nd bit in 8 should be flipped, which becomes
00001010
. How can I program this?

EDIT: I made a stupid mistake, I want to count starting from 0, so the 2nd bit in 8 flipped is actually
00001100
instead of
00001010
.

#include <stdio.h>
#include <stdlib.h>

void flipbit(int *p, int m) {
int digit;
digit = *p;

int bit;
bit = &m;

int result;

//printf("The numbers are %d %d", digit, bit);

printf("%d", result);
}

int main() {
int number1;
int number2;

printf("Give number and bit: ");
scanf("%d, %d",&number1, &number2);

flipbit(&number1, &number2);

return 0;
}

Answer

When checking your source code, there are mixture between pointer and value. To comply the call of your flipbit() function with the declaration, the call should be:

// first parameter is a pointer and second parameter is a value
flipbit(&number1, number2); // void flipbit(int *p, int m);

Inside the flipbit() function, the mixture continues because digit is a value and p is a pointer. The code should be:

int digit;

// 'digit' is a value and 'p' is a pointer
digit = p[0]; // 'digit' is the first value pointed by 'p'

Same error kind of error with the 'bit' parameter

int bit;

// 'bit' is a value and 'm' is a value
bit = m;

And the result to flip a bit is the XOR operation.

the bit number 2, so the 2nd

Due to your specification, you have to shift only of (bit - 1). So, in your case: 0x0001(or 0000.0000.0000.0001b) << (2 - 1) = 0x0002(or 0000.0000.0000.0010b)

result is 0x0010(or 0000.0000.0000.1000b) XOR 0x0002(or 0000.0000.0000.0010b) = 0x0012(or 0000.0000.0001.0010b).

int result;

result = digit ^ (0x0001 << (bit - 1));

Did you enter '9, 1' to comply with the scanf("%d, %d",..) ?