Disecting a binary number to store into separate variables in C++

Saint Nick

Lifer
Jan 21, 2005
17,722
6
81
My other thread about binary . . .

In the above thread, I used the decimal number 123?1111011 in binary. What I want to know is how can I disect 1111011 to store each individual 1 and 0 into its own variable? Meaning, going from left to right:

n1 = 1;
n2 = 1;
n3 = 1;
n4 = 1;
n5 = 0;
n6 = 1;
n7 = 1;

How can I do this using division and modulus operators only?
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Well, you could do it with division and modulus operators. But it would be much more direct to use bit shift operators & such.

I wrote a nice class for doing all sorts of operations on binary arrays of arbitrary size - very useful for genetic algorithms!
 

Saint Nick

Lifer
Jan 21, 2005
17,722
6
81
Originally posted by: Armitage
Well, you could do it with division and modulus operators. But it would be much more direct to use bit shift operators & such.

I wrote a nice class for doing all sorts of operations on binary arrays of arbitrary size - very useful for genetic algorithms!

I would love to use these "bit shift" operators, but we can't use anything past the chapter we are on. How can I disect this number using only division and modulus?
 

talyn00

Golden Member
Oct 18, 2003
1,666
0
0
Originally posted by: jndietz
Originally posted by: Armitage
Well, you could do it with division and modulus operators. But it would be much more direct to use bit shift operators & such.

I wrote a nice class for doing all sorts of operations on binary arrays of arbitrary size - very useful for genetic algorithms!

I would love to use these "bit shift" operators, but we can't use anything past the chapter we are on. How can I disect this number using only division and modulus?

Take the number 13, you wanted to conver this to binary. You can do something similiar to the following

TOP = LSB
13 / 2 = 6 R 1
6 / 2 = 3 R 0
3 / 2 = 1 R 1
1 / 2 = 0 R 1
BOTTOM = MSB

Reading it from bottom up, you get 1101 which is 13. You can easily write this program using a loop and an array to store the binary values.