Reputation: 45
I have created a small beginner program that converts decimal values to binary. However, only decimal values up to 32 bits are printing correctly.
#include <stdio.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
int main() {
static int b[64];
int l, r;
unsigned long long d;
scanf("%d", &d);
// determines number of bits to output
if (d <= EIGHT_BITS) {
l = 8;
printf("8bits\n");
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
printf("16bits\n");
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
printf("32bits\n");
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
printf("64bits\n");
}
// creates array
for (int i = 0; i < l; i++) {
r = d % 2;
d /= 2;
b[i] = r;
}
// reverses array for binary value
for (int j = l - 1; j >= 0; j--) {
printf("%d", b[j]);
}
return 0;
}
When I enter various decimal values up to the 64 bit unsigned long long, the decimals print with the corresponding binary value. However, somewhere between the 32 bit values and the 64 bit values, the numbers become incorrect.
I receive accurate 32 bit values when I define “d” with “unsigned long,” but when I change the type to “unsigned long long” to accommodate larger numbers, the 8, 16, and 32 bit values are no longer accurate, and neither are the 64 bit values.
Here is my output:
// correct
>> 357
16bits
0000000101100101
// correct
>> 4294967295
32bits
11111111111111111111111111111111
// incorrect
>> 18446744073709551615
64bits
0000000001000000000110100110111011111111111111111111111111111111
Upvotes: 2
Views: 335
Reputation: 223972
Here's the problem:
scanf("%d", &d);
The type of d
is unsigned long long
, but you're using %d
which expects the address of an int
. Using the wrong format specifier invokes undefined behavior.
The correct format specifier for an unsigned long long
is %llu
:
scanf("%llu", &d);
Upvotes: 4