วันพุธที่ 24 ตุลาคม พ.ศ. 2550

How do I output numbers as binary strings?

How do I output numbers as binary strings? We had some help from the standard C library to answer the question How do I input number as binary string? The standard library function strtoul() was available to do the work for us.

When it comes to outputting a numeric value of one of the integer types as a string of just 0's and 1's, however, we are strictly on our own. The code to do this is not very hard. Here is the code for displaying an unsigned char:

#include
#include
char *unsigned_char_to_text(char val){
unsigned char usc = (unsigned char)val;
unsigned char mask = UCHAR_MAX - (UCHAR_MAX >> 1);
static char result [CHAR_BIT + 1];
char *store = result;
while (mask) {
*store++ = (char)('0' + ((usc & mask) != 0));
mask >>= 1;
}
*store = '\0';
return result;
}

To generate a function to output an unsigned int as a binary string, just make the following changes to this function:

Change val to int and usc and mask to unsigned int.
Change the two references to UCHAR_MAX to UINT_MAX.
Change the expression "UCHAR_BIT + 1" for the array size to "sizeof(int) *UCHAR_BIT + 1".

To make a function to do the same for unsigned long, change val to long and usc and mask to unsigned long, change UCHAR_MAX to ULONG_MAX, and use "sizeof(long) * UCHAR_BIT + 1".

Warning about the returned string. The string used to store the characters in the unsigned_char_to_text is defined as a static array of characters inside the function. It must be static because local variables defined inside a function go out of scope and cease to exist once the function returns, so it is illegal and a bug to return a pointer to a local non static variable.

The fact that the string is static means that each call to the function uses the same string space and overwrites the string produced by a previous call. So if you use this function more than once in a program you should be careful to do the following:

Use the string immediately to display or write to a file, before calling the function again.
If you do need to keep the generated string for some time, and the function might be called again, copy the string.

ไม่มีความคิดเห็น: