### How to set a bit?

Hello,

I want to write a function that sets multiple bits.
Here is how it should look:
The user gives a positive integer, like 5. It then prints out the binary number
Then the user has to give place number of what bit he wants to set, for instance 6

It should look like this
 ``12`` ``````00000000 00000000 00000000 00000101 00000000 00000000 00000000 00100000``````

Then comes the setting part and it should look like this
`00000000 00000000 00000000 00100101`

I have already done the binary representation of a number.
But I don't know how I display the place I want to set and then actually set the bits.
Can someone help me out?
Here is my code so far:
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667`` ``````#include #include void Binair(int v) { int i; int mask = 1 << 31; for(i=1; i<=32; ++i) { putchar(((v & mask) == 0) ? '0' : '1'); v <<= 1; if(i % 8 ==0 &&i <=32) putchar(' '); } } void bitMask(int b) { int i; int bitmask; for(i=1; i<=32; ++i) { putchar((b & bitmask) ? '0' : '1'); if(i % 8 ==0 &&i <=32) putchar(' '); } } int main() { unsigned int v; unsigned int b; printf("Give a positive int:\t"); scanf("%d",&v); printf("Give the bit you want to set:\t"); scanf("%d",&b); if(v < 0) { printf("That is not a positive int"); Sleep(1000); return 0; } else { printf("Binary this is:\t"); binair(v); printf("\n"); printf("Bitmask:\t"); bitMask(b); } getchar(); getchar(); } ``````

It looks like Binair and bitMask is trying to do the same thing, that is to print the binary representation of a number.

To create the number that only has bit b set you can left shift 1 b steps. `1 << b`
Last edited on
 ``123456789101112131415161718192021222324`` ``````#include inline void setOn (int & x, int n) { x |= (1 << n); } inline void setOff(int & x, int n) { x &= ~(1 << n); } int main() { int x = 5; setOn(x, 6); std::cout << x << std::endl; setOff(x, 2); std::cout << x << std::endl; return 0; }``````

To add on to Peter87, i don't think you need the function bitMask. Given the fact that your Binair function is working, you can try:
 ``1234`` ``````unsigned int c = 1 << (b-1); Binair(c); printf("\n"); Binair(c | v);``````
Thank you for replying, my program works! thanks
Topic archived. No new replies allowed.