[英]using sscanf in C to turn a hex String into command arguments for bash
試圖制作一個十六進制解碼器以便從命令行文件中讀取參數,並且在C語言中我很容易操作字符串函數。 我的十六進制解碼器的用途是使我可以接受一個十六進制字符串,例如“ 2d6c002d6100f757372”,並將其變成一組用於bash的指令,在本例中為-l -a / usr。 但是,我的問題是,在我當前的代碼中,我只能分別從字符串中提取每個字符,因此我最終得到了10個字符,這些字符對bash shell毫無意義。 我理想地想要擁有的是
args[0] = binary_path
args[1] = "-l"
args[2] = "-a"
args[3] = "/usr"
args[4] = NULL
但我不知道如何將十六進制字符串中每個0x00之前的字符串分組在一起。 這是我到目前為止針對此問題的代碼:
int i = 0;
char *hexString = "2d6c002d6100f757372"
char *hexPtr = hexString;
unsigned int *result = calloc(strlen(hexString)/2 + 1, sizeof *result);
while (sscanf(hexPtr, "%02x", &result[i++])) {
hexPtr += 2;
if (hexPtr >= hexString + strlen(hexString))
break;
return result;}
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int hex2dec(int value) // used to convert a hex digit to decimal
{
if (isdigit(value))
return value - '0';
value = toupper(value); // to make the function more robust for various input
if ('A' <= value && value <= 'F')
return 10 + value - 'A';
return -1;
}
int main(void)
{
char const *hex_str = "2d6c002d61002f757372";
size_t hex_str_len = strlen(hex_str);
size_t len = hex_str_len / 2; // there are half as many characters than hex digits
char *str = calloc(len + 1, 1);
size_t str_count = 1;
for (size_t i = 0; i < len; ++i) {
str[i] = hex2dec(hex_str[i * 2]) * 16 + hex2dec(hex_str[i * 2 + 1]);
if (!str[i]) // at every 0-terminator
++str_count; // count a new string
}
char **split_str = malloc(str_count * sizeof(char*));
for (size_t i = 0, offset = 0; i < str_count; ++i) {
size_t len = strlen(str + offset);
split_str[i] = calloc(len + 1, 1);
strcpy(split_str[i], str + offset);
offset += len + 1;
}
free(str);
// Output:
for (size_t i = 0; i < str_count; ++i)
printf("\"%s\"\n", split_str[i]);
// Cleanup:
for (size_t i = 0; i < str_count; ++i)
free(split_str[i]);
free(split_str);
}
"-l"
"-a"
"/usr"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.