十六进制字符串到二进制字符串

时间:2016-11-09 02:31:20

标签: c binary hex converter

我正在尝试创建一个用户输入十六进制字符串的程序(“格式为3ecf,没有0x且没有大写字母”)下面的代码是我尝试复制用户输入的内容(地址)并存储其二进制文件binAddress中的等价物。

我该如何解决这个问题? 或者有更简单的方法吗?

<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag,
             RelativeSource={RelativeSource Self}}">

...

<MyControl:MyListViewItem .... Tag="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type MyControl:MyListViewView}}}"}" ...>

2 个答案:

答案 0 :(得分:1)

像这样解决:

#include <stdio.h>
#include <string.h>

char address[6+1];    //+1 for NUL
char binAddress[6*4+1];//+1 for NUL
void hexToBin(void);

int main(void){
    scanf("%6s", address);

    hexToBin();

    printf("%s\n", binAddress);
    return 0;
}

void hexToBin(){
    int i, j;

    for(j = i = 0; address[i]; ++i, j += 4){
        switch(address[i]){
        case '0': strcpy(binAddress + j, "0000"); break;
        case '1': strcpy(binAddress + j, "0001"); break;
        case '2': strcpy(binAddress + j, "0010"); break;
        case '3': strcpy(binAddress + j, "0011"); break;
        case '4': strcpy(binAddress + j, "0100"); break;
        case '5': strcpy(binAddress + j, "0101"); break;
        case '6': strcpy(binAddress + j, "0110"); break;
        case '7': strcpy(binAddress + j, "0111"); break;
        case '8': strcpy(binAddress + j, "1000"); break;
        case '9': strcpy(binAddress + j, "1001"); break;
        case 'a': strcpy(binAddress + j, "1010"); break;
        case 'b': strcpy(binAddress + j, "1011"); break;
        case 'c': strcpy(binAddress + j, "1100"); break;
        case 'd': strcpy(binAddress + j, "1101"); break;
        case 'e': strcpy(binAddress + j, "1110"); break;
        case 'f': strcpy(binAddress + j, "1111"); break;
        default:
            printf("invalid character %c\n", address[i]);
            strcpy(binAddress + j, "0000"); break;
        }
    }
}

答案 1 :(得分:0)

您不需要在char数组中存储十六进制。您可以通过带有说明符%x的scanf读取它 http://www.cplusplus.com/reference/cstdio/scanf/

然后将其转换为二进制(C字符串形式) how to print binary number via printf