十六进制转二进制c语言
时间: 2024-10-07 15:05:11 浏览: 71
C语言 进制转换
十六进制转换成二进制在C语言中可以使用位操作来实现,因为十六进制每一位对应四位二进制。下面是一个简单的C函数示例:
```c
#include <stdio.h>
// Function to convert hexadecimal to binary
void hexToBinary(char hex[], char bin[]) {
int len = strlen(hex);
for (int i = 0; i < len; i++) {
int decimal = hexval(hex[i]); // Convert each hex digit to its decimal equivalent
for (int j = 0; j < 4; j++, bin[i*4+j]) { // Shift the binary representation and add digits
bin[i*4+j] = decimal & 1; // Get the least significant bit
decimal >>= 1; // Shift decimal right by one bit
}
}
bin[len*4] = '\0'; // Add null terminator to binary string
}
// Function to get decimal value from a single hexadecimal character
int hexval(char c) {
switch (c) {
case '0': case '1': case '2': case '3':
return c - '0';
case '4': case '5': case '6': case '7':
return c - '4' + 8;
case '8': case '9':
return c - '8' + 16;
case 'A': case 'B': case 'C': case 'D':
return c - 'A' + 10;
case 'E': case 'F':
return c - 'E' + 14;
default:
return -1; // Invalid hexadecimal character
}
}
int main() {
char hex[] = "FF"; // Input hexadecimal number
char bin[17]; // Large enough buffer to hold binary representation with null terminator
hexToBinary(hex, bin);
printf("Hexadecimal: %s\nBinary: %s\n", hex, bin); // Print results
return 0;
}
```
这个程序首先将十六进制字符转换为十进制,然后逐位转换为二进制。请注意,这里假设输入的十六进制字符串有效。
阅读全文