If you know the bitwise operators it can be very simple.
You can rotate the bits and test for 1 or 0 using a mask if you AND 1 with the rotated number it will give you the bit then use a conditional statement to print either a 0 or a 1 to the screen.
Code:
int number=3;
int number_copy=number;
_rotr(number,1); //rotates number right _rotl() goes left
if(number & 1) //if number & 1 is true
{
putchar('1');
}
putchar('0');
you have to work with it a bit because if you shift it the wrong direction it prints it out in reverse but you get the idea
[edit]
OOPS wrong direction you wanted binary to decimal :D
You could just do the reverse. For each 1 or 0 you can use the mask to set the bits and then rotate.
Sorry am using Visual C++ compiler
_rotl() and _rotr() are supposed to mimic the assembly language instructions for rotating bits.
I suppose you could write your own using the bitwise shift operator>> and <<. Normally when you shift the bits left or right it just discards the bit and you eventually end up with 0. If you create a mask using the number for the bit you want to use (ie to test or set the 32nd bit set the mask=2^31) then you can use the following algorithm:
for rotating right
mask_lowbit=1; //2^0 the first bit set to 1
mask_highbit=21474836848; //2^31 the 32nd bit set to 1
test lowbit for 1 or 0 by ANDing (mask_lowbit & number)
if result is 0 then simply shift number to the right
if true then shift numbers to the right and set the 32nd bit by ORing(number | mask_highestbit)
just reverse the process for shifting left
Thank you for setting me straight prelude.
Your right. I just copied and paste one of my examples without thinking. I need to pay more attention to standards and compiler/op. Thank you. Anyway here is code example of home made functions.
Code:
unsigned int bit_rotate_right(unsigned int num, unsigned int numbits)
{
unsigned int lowbitmask=1; // mask for 1st bit
unsigned int highbitmask=2147483648; //mask for 32nd bit 2^31
for(int i=0;i<numbits; i++)
{
if(num & lowbitmask)
{
num=num>>1;
num=(num|highbitmask);
}
else
{
num=num>>1;
}
}
return num;
}
unsigned int bit_rotate_left(unsigned int num, unsigned int numbits)
{
unsigned int lowbitmask=1; // mask for 1st bit
unsigned int highbitmask=2147483648; //mask for 32nd bit 2^31
for(int i=0;i<numbits; i++)
{
if(num &highbitmask )
{
num=num<<1;
num=(num|lowbitmask);
}
else
{
num=num<<1;
}
}
return num;
}