So I'm making a binary->decimal program where i need to target a specific digit in the number which is inputed, so for instance if the input is 100110110, how do i target the fourth digit, in this case obviously being 1, and the fifth, sixth, ... how many ever digits there are?
Asked
Active
Viewed 197 times
0
-
[How do you set, clear, and toggle a single bit in C/C++?](http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c?rq=1) – Pavel P Apr 27 '17 at 18:08
-
do you have the binary in a string or in an int / long – pm100 Apr 27 '17 at 18:12
-
1Possible duplicate of [How do you set, clear, and toggle a single bit in C/C++?](http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c) – François Andrieux Apr 27 '17 at 18:14
2 Answers
0
If the input is a binary string, store the input in a string and process it using a loop
string num = "1001010";
int l = num.length();
for(int i=0; i<l; i++) {
// num[i] is the (i+1)th bit from left;
}

Rajeev Singh
- 3,292
- 2
- 19
- 30
-1
how many ever digits there are?
these are called bits. To find number of bits in a variable use sizeof operator that returns number of bytes.
sizeof(variable) * 8
how do i target the fourth digit
you can test a bit with operator&
:
if (8 == (variable & 8))
...
There are already detailed answers on how to do that: How do you set, clear, and toggle a single bit in C/C++?
-
This answer does not address how to read or write individual bits, or access them as OP puts it. – François Andrieux Apr 27 '17 at 18:11
-
@FrançoisAndrieux why would you address something that have been done properly years ago. I added link in the comment. – Pavel P Apr 27 '17 at 18:13
-
If you know that this question has already been correctly answered before and have a link to that answer, why did you not vote for duplicate? – François Andrieux Apr 27 '17 at 18:14
-
@FrançoisAndrieux Because it asks also about number of digits. And you vote down because of what?.. – Pavel P Apr 27 '17 at 18:15
-
can someone link me something about the basics of bits, havent read into them much; also is there any library you need to include for bits? – Tejas K Apr 27 '17 at 18:17
-
@TejasK Google for `Bits Manipulation in C` or something like that. This is usually covered in beginner programming books. No library is needed for that – Pavel P Apr 27 '17 at 18:19