PPP PPP - 10 months ago 55
C Question

Simultaneous operation on several array-indice in C

I have a 1 byte array in C, like

uint8_t array[128]

I would like to perform an operation in which I take 4 entries of the array, do an operation on them and then save those 4 entries at another index. Basically in Pseudocode:

array[4 to 7] = 0x01020304 XOR array[0 to 3]

Is there an elegant way of doing this in C?


A way that's well-defined in the C standard is to

  1. Declare a uint32_t. Call it foo, say.

  2. memcpy the relevant part of array to foo.

  3. Perform the XOR.

  4. memcpy that back to array.

This approaches elegance if you wrap this up in a function. Note that the results of this operation will be endianness-sensitive so will vary from platform to platform.

Alternatively, if you put endianness concerns on the back-burner, you could split up 0x01020304 into 4 bytes and perform the operation byte by byte directly on array.

Other approaches include type punning through a union or ditching the language entirely and using inline assembly (using the byte-by-byte approach). Note that making arbitrary conversions and casts in C is often a hair's breadth from rendering the behaviour of your code undefined, so be careful if you go down that path.