how can I convert the x position digit of binary number to for example 1 or 0 without using loop... x is an integer number and position is where you change the binary number
Asked
Active
Viewed 341 times
-2
-
You could use bit-shift; `unsigned value = (x >> position) & 1;`. – trojanfoe Nov 21 '21 at 16:29
-
1An efficient way is [bit masking](https://stackoverflow.com/q/10493411/2472827). – Neil Nov 21 '21 at 16:31
-
Or if you don't want to write the bitmasking code yourself : https://en.cppreference.com/w/cpp/utility/bitset – Pepijn Kramer Nov 21 '21 at 16:36
-
1It's important to understand that there isn't such a thing as a "binary number". Binary is a *way to represent* the number. If I write `23` or `0x17` or `0x10111` or `twenty-three` I am talking about the same thing; and by writing it in different ways, I *didn't change* the thing. – Karl Knechtel Nov 21 '21 at 16:46
-
@royanmaeri Did the answer help or do you want me to explain anything in more detail? – Ted Lyngmo Nov 21 '21 at 18:35
2 Answers
3
- Toggle the bit
pos
innum
:num ^= 1ULL << pos; // ^ is xor
- Set the bit
pos
innum
:num |= 1ULL << pos; // | is bitwise or
- Clear the bit
pos
innum
:num &= ~(1ULL << pos); // & is bitwise and, ~ is bitwise not

Ted Lyngmo
- 93,841
- 5
- 60
- 108
0
You can use this code to change the x-th digit.
#include <stdio.h>
int main()
{
int input;
int x=2;//number of the digit that you want to change
int y=0;//x-th digit will be changed to this
scanf("%d",&input);
int left_digits; //the digits left to the (x-1)-th digit
int right_digits;//the x-1 first digits
left_digits=input>>x-1;
right_digits=input-(left_digits<<x-1);
left_digits-=left_digits%2;
left_digits+=y;
int ans=(left_digits<<x-1)+right_digits;
printf("%d",ans);
}
-
This is unnecessarily complicated. `if (y) input |= 1 << x; else input &= ~1 << x;` (suggested in the other answer) should do the same thing. – HolyBlackCat Nov 29 '21 at 10:42