简体   繁体   English

将二进制char []转换为十六进制char []

[英]Converting a binary char[] to a hexadecimal char[]

I have unsigned char[] that contains binary text. 我有包含二进制文本的unsigned char []。 I need to convert this binary text into hexadecimal. 我需要将此二进制文本转换为十六进制。 I have managed to do just this and output the result to a file. 我已经做到了这一点,并将结果输出到文件中。 However, for speed reasons, I would like to directly output this to a char[] so I can further manipulate it. 但是,出于速度原因,我想直接将其输出到char [],以便进一步操作它。 The following is the code that writes out to the file: 以下是写入文件的代码:

for( i = 0; i < rsa.len; i++ )
fprintf( f, "%02X%s", buf[i],
             ( i + 1 ) % 16 == 0 ? "\r\n" : " " );

And buf is defined as follows: buf的定义如下:

unsigned char buf[512];

The output to the file looks like: 该文件的输出如下所示:

11 51 64 36 7A 9D 6C E8 F5 5C B2 29 2D 2F 1B 87
0A 20 23 3F B4 B0 41 5F A1 5F 54 6A C4 44 49 4B
58 C1 91 67 7D 7F 70 8D 20 9A 86 06 89 3A A8 2A
26 18 7A CE AB C0 7B 2A D7 A4 B2 5B C6 76 EB EA
90 F9 59 6C 78 4A 7C B2 A6 AE 46 3E E0 A7 A7 6A
F6 81 E3 70 78 B7 0D CC 8B D2 2C 23 42 EB 3B 90
88 15 AC 4C 84 FD 24 40 4F 08 C8 36 89 04 E4 5E
F1 AF CF FE 68 75 38 9C 75 0A 22 C2 44 49 35 A2

If it matters buf is the binary output of an 512 bit RSA encryption. 如果重要的话,buf是512位RSA加密的二进制输出。

I was thinking of using sprintf() to print to a char[] in hexadecimal but I can't seem to get it to work correctly. 我当时在考虑使用sprintf()以十六进制打印到char [],但是我似乎无法使其正常工作。

The best-performant solution would be to write HEX yourself. 最佳性能的解决方案是自己编写HEX。 This is not a difficult task if you use a lookup table: 如果您使用查找表,这并不是一项艰巨的任务:

unsigned char buf[512];
char res[2048];
static const char* hex_lookup = "0123456789ABCDEF";
char *p = res;
for (int i = 0 ; i != 512 ; i++) {
    *p++ = hex_lookup[buf[i] >> 4];
    *p++ = hex_lookup[buf[i] & 0x0F];
    if ((i+1)%16) {
        *p++ = ' ';
    } else {
        *p++ = '\r';
        *p++ = '\n';
    }
}
*p = '\0';

You seem to be confused about bases and storage types. 您似乎对基本和存储类型感到困惑。 A char only stores binary data, everything else is in how you interpret it. char仅存储二进制数据,其他所有内容都取决于您如何解释它。

If what you're trying to do is store the ascii representation of a hexadecimal number in a char, you could do this straightforwardly by doing 如果您要执行的操作是将十六进制数字的ascii表示形式存储在char中,则可以通过执行以下操作直接完成此操作

#define TOHEX(c) ((c) > 9 ? (c) - 10 + 'a' : (c) + '0')
char high = TOHEX((c >> 4) & 0xf);
char low = TOHEX(c & 0xf);

You would need two chars to store every character. 您将需要两个字符来存储每个字符。

You can use snprintf in a loop: 您可以在循环中使用snprintf

char* output = malloc(rsa.len * 3 + 1); // each number takes three characters to represent

char* cur = output;

for (i = 0; i < rsa.len; ++i)
    cur += snprintf(cur, sizeof(output) - (cur - output) - 1, "%02X%s", buf[i], (i + 1) % 16 ? " " : "\n");

// output is now a C-string holding 01 C2 etc

free(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM