Padding zeroes on to a binary number

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) {
	long int n=2;
	while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");
 
    n >>= 1;
}
printf("\n");
	return 0;
}
@vasiqhair

Actually, the binary of 2, is 10, or 0010. You have to turn the results you are getting around.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream> // For use of the std::cout
#include <stdio.h>
#include <math.h>
 
int main(void)
{
	long int 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;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <math.h>

const unsigned bits = 4;

void print_bits(unsigned value)
{
    unsigned mask = 1 << (bits-1);

    while (mask)
    {
        printf("%d", (mask & value) != 0);
        mask >>= 1;
    }
}


int main(void)
{
    for (unsigned i = 0; i < (1 << bits); ++i)
    {
        print_bits(i);
        printf("\n");
    }
}
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111


Topic archived. No new replies allowed.