1

我有以下数据类型的结果缓冲区:

 char result[16];

问题是,结果是以 4 个 32 位的块计算的,需要分配给 128 位结果字符。

int res_tmp[0] = 0x6A09E667;
int res_tmp[1] = 0x6A09E612;
int res_tmp[2] = 0x6A09E432;
int res_tmp[3] = 0x6A09E123;

理想情况下,C 中应该有类似连接运算符的东西,例如,

result = res_tmp[0] || res_tmp[1] || res_tmp[2] || res_tmp[3];

最后,需要通过套接字发送结果,如下所示:

while((connection_fd = accept(socket_fd, 
                          (struct sockaddr *) &address,
                          &address_length)) > -1)
{
  n = write(connection_fd, result, strlen(result));
  if (n < 0) printf("Error writing to socket\n");            
  close(connection_fd);
  break;  
}

任何人都知道在 128-bir 结果中连接 32 位字的最简单语法char吗?

谢谢,帕特里克

4

3 回答 3

5

您必须确定char数组是按大端还是小端顺序表示结果。如果你的处理器和数组的字节序恰好重合,你可以使用union

union myunion
{
    char result[16];
    int res_tmp[4];
};

然后你根本不需要复制。

如果您需要处理器的相反字节序,您可以使用htonl

for (i = 0; i < 4; i ++) res_tmp[i] = htonl(res_tmp[i]);
于 2012-11-13T18:41:24.720 回答
1

为什么不直接使用memcpy

memcpy(result, res_tmp, sizeof(res_tmp));

另请注意,strlen对于以空结尾的字符串,您应该将 sizeof 用于静态缓冲区:

n = write(connection_fd, result, sizeof(result));

当然你也可以发送res_tmp

n = write(connection_fd, (char*)res_tmp, sizeof(res_tmp));
于 2012-11-13T18:20:46.767 回答
-1

基本上标准技术是创建一个 int 指针并将其指向 char 数组,然后用它来写入数据。像这样的东西

int temp_res[4]; //the calculated ints
char result[16]; //the target buffer
int *ptr=(int *)result;
for (int i=0;i<4;i+=1) {
  *ptr=temp_res[i];
  ptr++; //move up a int size because ptr is an int type
}
于 2012-11-13T18:16:07.727 回答