Reputation: 1019
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.
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, e.g.,
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
?
Thanks, Patrick
Upvotes: 1
Views: 608
Reputation: 41180
You must decide if the char
array is representing the result in big-endian or little endian order. If the endian-ness of your processor and the array happen to coincide, you can use a 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
for (i = 0; i < 4; i ++) res_tmp[i] = htonl(res_tmp[i]);
Upvotes: 5
Reputation: 7476
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 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
}
Upvotes: -1
Reputation: 17312
why not just use memcpy
?
memcpy(result, res_tmp, sizeof(res_tmp));
Also note that strlen
is for null terminated strings, you should use sizeof for static buffer:
n = write(connection_fd, result, sizeof(result));
And of course you could just send res_tmp
n = write(connection_fd, (char*)res_tmp, sizeof(res_tmp));
Upvotes: 1