patterncMinor
Byte-to-binary conversion function
Viewed 0 times
conversionbytefunctionbinary
Problem
My implementation of a binary-to-bits converting function:
Output:
#include
#include
unsigned char *return_byte (unsigned char source)
{
static unsigned char byte[CHAR_BIT];
unsigned char *p = byte, i;
for(i = 0; i 0);
return p;
}
int main(void)
{
unsigned char val = 200;
printf("Value:\t%i\nBinary:\t%s", val, return_byte(val));
return 0;
}Output:
Value: 200
Binary: 00010011
Solution
-
-
A
-
Using an
-
A boolean expression as
-
You do not null-terminate the resulting string. The fact that your test succeeded is a sheer (un)luck.
-
You probably know that returning static makes the code non-reentrant and thread-unsafe. You may want to let client provide a space for a resulting string.
return_byte doesn't tell much what the function is intended to do. btoa would be more in line with C naming convention (akin to itoa)-
A
p variable is pretty much useless. Considerstatic unsigned char byte[CHAR_BIT];
unsigned char i;
for(i = 0; i 0);
return byte;-
Using an
unsigned char for indexing is questionable. In any case it doesn't buy you much against a native int.-
A boolean expression as
+ operand may raise some eyebrows (true is guaranteed to be a non-zero in an arithmetic context, but it is not guaranteed to be 1). I recommend to force an arithmetic value by right-shifting source instead of left-shifting the mask:for(i = 0; i >= 1;
}-
You do not null-terminate the resulting string. The fact that your test succeeded is a sheer (un)luck.
-
You probably know that returning static makes the code non-reentrant and thread-unsafe. You may want to let client provide a space for a resulting string.
Code Snippets
static unsigned char byte[CHAR_BIT];
unsigned char i;
for(i = 0; i < CHAR_BIT; i++)
byte[i] = '0' + ((source & (1 << i)) > 0);
return byte;for(i = 0; i < CHAR_BIT; i++) {
byte[i] = '0' + (source & 1);
source >>= 1;
}Context
StackExchange Code Review Q#82303, answer score: 3
Revisions (0)
No revisions yet.