c语言合法的16进制数组转2进制数组,再转成int型数组,例如:0xf4转成11110100
时间: 2023-10-19 11:20:09 浏览: 124
十进制,十六进制,BCD码相互转换C程序.doc
可以使用位运算来实现该功能。以下是一个示例代码:
```c
#include <stdio.h>
void hexToBinaryArray(unsigned char hexArr[], int hexArrSize, unsigned char binaryArr[], int binaryArrSize) {
int i, j;
for (i = 0; i < hexArrSize; i++) {
for (j = 0; j < 8; j++) {
binaryArr[i * 8 + j] = (hexArr[i] & (1 << (7 - j))) ? '1' : '0';
}
}
}
void printBinaryArray(unsigned char binaryArr[], int binaryArrSize) {
int i;
for (i = 0; i < binaryArrSize; i++) {
printf("%c", binaryArr[i]);
}
printf("\n");
}
void binaryArrayToIntArray(unsigned char binaryArr[], int binaryArrSize, int intArr[], int intArrSize) {
int i, j, k;
for (i = 0; i < intArrSize; i++) {
intArr[i] = 0;
for (j = 0; j < 8; j++) {
k = i * 8 + j;
if (k >= binaryArrSize) {
break;
}
intArr[i] = (intArr[i] << 1) + (binaryArr[k] - '0');
}
}
}
void printIntArray(int intArr[], int intArrSize) {
int i;
for (i = 0; i < intArrSize; i++) {
printf("%d ", intArr[i]);
}
printf("\n");
}
int main() {
unsigned char hexArr[] = {0xf4};
int hexArrSize = sizeof(hexArr) / sizeof(unsigned char);
unsigned char binaryArr[8 * hexArrSize];
int binaryArrSize = sizeof(binaryArr) / sizeof(unsigned char);
int intArr[hexArrSize];
int intArrSize = sizeof(intArr) / sizeof(int);
hexToBinaryArray(hexArr, hexArrSize, binaryArr, binaryArrSize);
printf("Binary array: ");
printBinaryArray(binaryArr, binaryArrSize);
binaryArrayToIntArray(binaryArr, binaryArrSize, intArr, intArrSize);
printf("Int array: ");
printIntArray(intArr, intArrSize);
return 0;
}
```
该程序先将16进制数组转换成二进制数组,然后将二进制数组转换成int型数组。运行结果如下:
```
Binary array: 11110100
Int array: 244
```
阅读全文