The following piece of code is supposed to output the binary representation of a given integer and it does exactly that. However, if the given integer is 2, then output is 01. Is there a way to make the program output 0001. I am working on a C program that outputs 4-bit gray code. Any help is much appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <stdio.h>
#include <math.h>
int main(void) {
longint n=2;
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
return 0;
}
#include <iostream> // For use of the std::cout
#include <stdio.h>
#include <math.h>
int main(void)
{
longint n=2; // Change to a number from 0 thru 15
int place=3;// Change to 7 for a 8 bit number, 0 to 255
int code[4]={0}; // Change 4 to 8, for an 8 bit number
while (n) {
if (n & 1)
code[place]=1;
else
code[place]=0;
n >>= 1;
place--;
}
for(place=0;place<4;place++) // Change the 4 to 8, if using an 8 bit number
std::cout << code[place];
//Not sure how to use printf{} to print data
printf("\n");
return 0;
}