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
1
2
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <windows.h>

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
   
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:
1
2
3
4
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.