问题
I am searching a way to convert hex char to bytes like \x90\x0d\x41 and when I use printf(), binary data are printed?
char *hex = "909090904241";
when I need to get \x90\x90\x90\x90\x42\x42 and when I print I get binary data.
回答1:
Loop through the string and append to a new string a piece with \x added infront like this:
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);
}
回答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);
Notes that buf isn't nul-terminated. I didn't see the point of making it nul-terminated string when the input could be "000000".
回答3:
For each character in the string, first convert it to a number by subtracting its ASCII by either the character '0' or 'A'. Then assign each value into the target array, shifting as necessary.
The below assumes ASCII, and that the input string contains only characters in the range 0-9 and A-F.
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");
Output:
90 90 90 90 42 41
回答4:
so basically I have a variable which contains hex bytes and when I print them I obtain binary representation
#include<stdio.h>
char *hex_bytes = "\x90\x90\x90\x41";
int main () {
printf(hex_bytes);
return 0 ;
}
I wanna do the same with hex chars like that
char *hex = "9090904241";
Thank you , HM
来源:https://stackoverflow.com/questions/48508787/how-to-convert-hex-char-into-bytes-like-x90-x90