Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将输入字符串转换为十六进制不会产生正确的大小_C_String_Memory_Hex_Shared - Fatal编程技术网

C 将输入字符串转换为十六进制不会产生正确的大小

C 将输入字符串转换为十六进制不会产生正确的大小,c,string,memory,hex,shared,C,String,Memory,Hex,Shared,我正在尝试将输入字符串从管道转换为十六进制,输入是8KB,但转换的十六进制只有6KB,我打印出正常的输入,正确的行就来了。我还尝试将十六进制字符串写入共享内存,可能我的问题是内存指针,但我不确定 但是,对于小的输入,它正确地输出十六进制,我被卡住了 字符串到十六进制: void stringtohex(char *input, char *output) { int loop; int i; i = 0; loop = 0; while (input

我正在尝试将输入字符串从管道转换为十六进制,输入是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;
)是错误的。函数
read
不了解字符串。它只是尝试读取
缓冲区大小
字节。因此,在一次
read
中,您可能会在
s
中得到少于一个或多个字符串,但不太可能只得到一个字符串(正如代码假设的那样)

还请注意,您从未在代码中使用
num
。这也很奇怪,因为
num
包含实际存储在
s
中的字节数。考虑使用<代码> Num < /Cord>来控制要转换的字节数。

或者,如果您真的想对字符串进行操作,请查看
fgets

顺便说一句:检查sprintf返回的内容。。。你会发现它很有用;-)

BTW:您也可以考虑<代码> STRCAT<代码>,而不是<代码> SeaTrf

正确的解决方案可能取决于输入数据,但如下所示:

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;
}

您确定
s
是否终止了
'\0'
吗?我实际上没有。请提供一个文件内容的示例。我打印了ptr,十六进制,但它们看起来都很好。然而,在增加ptr后,我想有些东西丢失了。@Harunasmaz从打印
num
len
开始。他们平等吗?我想他们没有。@Harunasmaz你的输入看起来怎么样?是一个长字符串还是多个字符串?缓冲区大小的值是多少?缓冲区大小是64 KB,输入文件包括4个段落,只有文本。输出为emptynum=len,strlen(十六进制)为len的两倍
        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);