[英]Converting input string to hex does not produce correct size
我正在嘗試將輸入字符串從管道轉換為十六進制,輸入為 8KB 但轉換后的十六進制僅為 6KB,我打印出正常輸入並且正確的行即將到來。 我還嘗試將該十六進制字符串寫入共享內存,也許我的問題是內存指針,但我不確定。
但是,它為小輸入正確打印出十六進制,我被卡住了。
字符串轉十六進制:
void stringtohex(char *input, char *output) {
int loop;
int i;
i = 0;
loop = 0;
while (input[loop] != '\0') {
sprintf((char*)(output + i), "%02X", input[loop]);
loop += 1;
i += 2;
}
//insert NULL at the end of the output string
output[i++] = '\0';
}
閱讀部分:
int num;
char s[BUFFER_SIZE];
while ((num = read(fd, s, BUFFER_SIZE)) > 0) {
//fprintf(stderr, "input: \n%s\n", s);
int len = strlen(s);
char hex[(len * 2) + 1];
stringtohex(s, hex);
sprintf(ptr_child_2, "%s", hex);
ptr_child_2 += strlen(hex);
}
這里ptr
是映射到共享內存的void *
。
使用read
將數據讀入s
然后將s
視為字符串(例如,您正在調用strlen(s);
)是錯誤的。 函數read
不知道字符串。 它只是嘗試讀取BUFFER_SIZE
字節。 因此,在一次read
,您可能會在s
中獲得少於一個字符串或多個字符串,但您不太可能只獲得一個字符串(正如您的代碼所假設的那樣)。
另請注意,您從未在代碼中使用num
。 這也很奇怪,因為num
保存了實際存儲在s
的字節數。 考慮使用num
來控制要轉換的字節數。
或者,如果您真的想對字符串進行操作,請查看fgets
。
順便說一句:檢查sprintf
返回什么......你會發現它很有用;-)
順便說一句:你也可以考慮strcat
而不是sprintf
正確的解決方案可能取決於輸入數據,但如下所示:
char* stringtohex(char* input, char* output, int num)
{
int loop=0;
while(loop < num)
{
sprintf(output, "%02X", input[loop]);
loop+=1;
output += 2;
}
//insert NULL at the end of the output string
*output = '\0';
return output;
}
閱讀部分注意: ptr_child_2
必須指向一個空字符串才能開始:
char RESULT[SOME_SUFFICIENT_BIG_NUMBER] = ""; // Or dynamic allocation
char* ptr_child_2 = RESULT;
int num;
char s[BUFFER_SIZE];
while((num = read(fd, s, BUFFER_SIZE)) > 0)
{
ptr_child_2 = stringtohex(s, ptr_child_2, num);
}
printf("%s\n", RESULT);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.