///
#include <stdio.h>
void
ConvertNumberToBinary(int Number, int *Array)
{
for(int I = 0;
I < 32;
++I)
{
int ZeroOrOne = Number%2;
if(ZeroOrOne < 0)
{
ZeroOrOne = 1;
}
*(Array + I) = ZeroOrOne;
Number = (Number >> 1);
}
}
int main()
{
int Number = 5;
int NumberInBinary[32] = {};
ConvertNumberToBinary(Number, NumberInBinary);
return(0);
}
///
A way to convert a number to binary is to use the mod operator, this thing -> % will give you the remainder of a divide for whole numbers. For example (4%3) will give you a remainder of 1. (3 goes into 4 one time, there is a remainder of 1 since 1 can't be divided by 3)
What's really useful about mod in solving this problem is it can effectively tell you the least-significant bit of any number in binary. The least significant bit representing 2^0 or 1 when turned on.
In order to do this all you have to do is divide any number by 2 and the remainder of that divide will either give you ZeroOrOne which maps directly to the least significant bit of any binary number.
I.e 000011001
^ Any number Mod by 2 (Number%2) will tell you the value for this bit
So in the code that's exactly what happens, we pass in a Number to the "ConvertNumberToBinary" function and once we start looping through our array of numbers, we take the Number we passed in, we Mod it by 2, and store that remainder in the ZeroOrOne variable, the we write to the array using that variable.
A second thing we do is we take the number and shift it down by one to remove the least-significant bit so we can see the data for the next bit.
Here's the steps viewing the number 5 in binary
0101
^ This Number%2 will be 1, we store that in the array, then we shift
0010 --- 1 < This 1 has been shifted out
^ We now mod this by 2 and check its value, it is zero, we store zero into the array then shift
0001 --- 0 < This 0 has been shifted out
^ We mod by two again and get 1, we store that in the array, then we shift.
0000 --- 1 < This 1 has been shifted out
--- Repeat until it's been done 32 times
--- Reach the end of the loop then break out of the function and the
array will have the result in binary
(it will be in little endian though - least significant bit will be the first array element)
And that's everything so far, two things to mention though, the function only works for arrays greater than 32 elements, otherwise it will break.
And the other thing is this code
if(ZeroOrOne < 0)
{
ZeroOrOne = 1;
}
If you pass in a negative number and mod it by two there will be a remainder, but the remainder will be -1 which isn't a binary value, so I just set ZeroOrOne to 1 if it was negative