Reputation: 11
When you have to convert a number from base 16 to base 2, what is the difference between lowercase and uppercase letters? (ex: 0Xa5B
)
I thought there was no difference, but I'm not sure.
Upvotes: 1
Views: 241
Reputation: 144695
There is no difference between upper and lower case in this context. The C language grammar and the library functions strtol()
and similar accept both upper and lower case letters for the 0x
or 0X
prefix and the digits greater than 9
in any combination.
You can convert the string to an unsigned long
with strtoul()
and you will need a custom function to convert the resulting integer to its binary representation as a string.
Here is an example:
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Convert an unsigned long to a string of binary digits.
* if the destination array is too short, truncate the high order bits;
* leading zeroes are omitted (except the last one for the value 0).
*/
char *convert_to_binary(char *dest, size_t size, unsigned long value) {
if (size > 0) {
size_t i = size;
dest[--i] = '\0';
while (i > 0) {
dest[--i] = '0' + (value & 1);
value >>= 1;
if (value == 0) /* remove this test if you want leading zeroes */
break;
}
if (i > 0) {
memmove(dest, dest + i, size - i);
}
}
return dest;
}
int main() {
char buf[sizeof(unsigned long) * CHAR_BIT + 1];
unsigned long value;
const char *str = "0Xa5B";
char *p;
/* convert the hex string to a number */
errno = 0;
value = strtoul(str, &p, 16); /* 0x prefix is ignored for base 16 */
/* check for conversion errors */
if (p == str) {
fprintf(stderr, "not a number: %s\n", str);
return 1;
}
if (*p != '\0') {
fprintf(stderr, "extra characters: %s\n", str);
return 1;
}
if (errno != 0) {
/* range error */
fprintf(stderr, "conversion error: %s: %s\n", str, strerror(errno));
return 1;
}
convert_to_binary(buf, sizeof buf, value);
printf("%s -> %s\n", str, buf);
return 0;
}
Upvotes: 1