我正在寻找一种方法将十六进制字符转换为像\ x90 \ x0d \ x41这样的字节,当我使用printf时,会打印二进制数据吗?
char *hex = "909090904241";
当我需要获取'\ x90 \ x90 \ x90 \ x90 \ x42 \ x42'并且当我打印时我得到二进制数据
谢谢,HM
答案 0 :(得分:2)
int hex_to_bytes(const char* hex, uint8_t** buf_ptr, size_t** len_ptr) {
size_t len = strlen(hex);
if (len % 2)
goto error1;
len /= 2;
char* buf = malloc(len);
char hex_byte[3];
hex_byte[2] = 0;
for (size_t i=len; i--; ) {
hex_byte[0] = *(hex++);
hex_byte[1] = *(hex++);
char* end_ptr;
buf[i] = strtoul(hex_byte, &end_ptr, 16);
if (end_ptr != hex_byte+2)
goto error2;
}
*buf_ptr = buf;
*len_ptr = len;
return 1;
error2:
free(buf);
error1:
*buf_ptr = NULL;
*len_ptr = 0;
return 0;
}
uint8_t* buf;
size_t len;
if (!hex_to_bytes(hex, &buf, &len)) {
... handle error ...
}
... Use buf and len ...
free(buf);
注意buf
没有终止。当输入为"000000"
时,我没有看到将其作为以空字符结尾的字符串的重点。
答案 1 :(得分:0)
对于字符串中的每个字符,首先通过字符 at iTextSharp.tool.xml.pipeline.AbstractPipeline.GetLocalContext(IWorkerContext context)
at iTextSharp.tool.xml.pipeline.html.HtmlPipeline.Close(IWorkerContext context, Tag t, ProcessObject po)
at iTextSharp.tool.xml.XMLWorker.EndElement(String tag, String ns)
或'0'
减去ASCII来将其转换为数字。然后将每个值分配到目标数组中,并根据需要进行移位。
以下假设为ASCII,输入字符串仅包含0-9和A-F范围内的字符。
'A'
输出:
char *str="909090904241";
unsigned char a[strlen(str)/2+1] = {0};
int i;
for (i=0;i<strlen(str);i++) {
unsigned char num = (str[i] >= '0' && str[i] <= '9') ? str[i] - '0' : str[i] - 'A' + 10;
a[i/2] |= num << (4 * (1 - (i % 2))); // shift even index bits by 4, odd index by 0
}
for (i=0;i<strlen(str)/2+1;i++) {
printf("%02x ", a[i]);
}
printf("\n");
答案 2 :(得分:0)
所以基本上我有一个包含十六进制字节的变量,当我打印它们时,我获得二进制表示
#include<stdio.h>
char *hex_bytes = "\x90\x90\x90\x41";
int main () {
printf(hex_bytes);
return 0 ;
}
我想用这样的十六进制字符做同样的事情
char *hex = "9090904241";
谢谢你,HM
答案 3 :(得分:-1)
循环遍历字符串并附加到一个新字符串,其中添加了const char *hex = "909090904241";
char* result = malloc((strlen(hex) * 2 + 1)* sizeof(char));
result[0] = 0;
char piece[] = "\\x00";
for (int i = 0; i < strlen(hex); i+=2) {
piece[2] = hex[i];
piece[3] = hex[i+1];
strcat(result, piece);
}
的字段,如下所示:
{{1}}