简体   繁体   English

在C中的16个char数组中并置32位int块

[英]Concatenating 32-bit int chunks in 16 char array in C

I have a result buffer of the following data type: 我有以下数据类型的结果缓冲区:

 char result[16];

The problem is, that the result is computed in 4 chunks of 32 bits each, that need to be assigned to the 128-bit result char. 问题是,结果是按4个块(每个32位)计算的,需要将其分配给128位结果char。

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

Ideally, there should be something like an concatenation operator in C, eg, 理想情况下,C中应该有类似串联运算符的东西,例如,

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

Finally, the result needs to be send over a socket as follows: 最后,需要通过套接字发送结果,如下所示:

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

Anyone knows the easiest syntax for concatenating the 32-bit words in the 128-bir result char ? 任何人都知道将128位结果char的32位字连接起来的最简单语法吗?

Thanks, Patrick 谢谢,帕特里克

You must decide if the char array is representing the result in big-endian or little endian order. 您必须确定char数组是以大端还是小端顺序表示结果。 If the endian-ness of your processor and the array happen to coincide, you can use a union : 如果处理器和数组的字节序恰好重合,则可以使用union

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

Then you don't have to copy at all. 然后,您根本不必复制。

If you need the opposite endian-ness of your processor, you can use htonl 如果需要与处理器相反的字节htonl ,则可以使用htonl

for (i = 0; i < 4; i ++) res_tmp[i] = htonl(res_tmp[i]);

why not just use memcpy ? 为什么不只使用memcpy呢?

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

Also note that strlen is for null terminated strings, you should use sizeof for static buffer: 另请注意, strlen用于以null结尾的字符串,您应该将sizeof用于静态缓冲区:

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

And of course you could just send res_tmp 当然,您可以发送res_tmp

n = write(connection_fd, (char*)res_tmp, sizeof(res_tmp));

Basically the standard technique is to create an int pointer and point it at the char array, then use it to write the data in. Something like this 基本上,标准技术是创建一个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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM