I've been trying to solidify my understanding of the binary number system by writing code. So, I tried to write a function with what I currently understand about the binary system that returns a string representation of the binary number representing the input.
Any feedback regarding how I may optimize the program is greatly appreciated. Thanks!
char *uint32_to_binarystr(uint32_t n) {
if (n != UINT32_MAX) {
int expb2 = 0; // Exponent of 2.
static char binarystr[33]; // 32 bits + 1 termination NULL char.
binarystr[32] = '\0'; // Add terminating NULL char.
memset(binarystr, '0', 32); // Initialize 32-bit string as 0.
while (n != 0) { // Continue until n has been completely represented by a sum of powers of 2.
while (1 << expb2 <= n) { expb2++; } // Find the power of 2 that yields a result greater than n.
expb2 -= 1; // Once this number is found, we are sure that the previous power yields the largest power of 2 less than n.
n -= 1 << expb2; // We've found a power of 2 to represent this "chunk" of n. Reduce n by the same amount.
binarystr[31 - expb2] = '1'; // Set the bit at the index with expb2 digits following it to 1.
expb2 = 0; // Reset exponent of 2 and repeat.
}
return binarystr;
} else {
/*
In the case that UINT32_MAX is to be represented, just return hard-coded string.
Why?
A 32-bit shift is not doable in some cases:
https://stackoverflow.com/questions/7401888/why-doesnt-left-bit-shift-for-32-bit-integers-work-as-expected-when-used
*/
static char binarystr[33];
binarystr[32] = '\0';
memset(binarystr, '1', 32);
return binarystr;
}
}
x % base
;x /= base;
and store the digits in reverse. \$\endgroup\$test(strcmp(uint32_to_binarystr(0), "0000..0000") == 0)
, wheretest
is anassert
-like function or macro for testing. Write a bunch of correct tests and then massage the code until they all pass. \$\endgroup\$