Patrick - 1 year ago 61

C Question

The code is from an open source project of sha256,

`uint64_t swapE64(uint64_t val) {`

uint64_t x = val;

x = (x & 0xffffffff00000000) >> 32 | (x & 0x00000000ffffffff) << 32;

x = (x & 0xffff0000ffff0000) >> 16 | (x & 0x0000ffff0000ffff) << 16;

x = (x & 0xff00ff00ff00ff00) >> 8 | (x & 0x00ff00ff00ff00ff) << 8;

return x;

}

the function is not complex, but I don't know its mathematical means and usage.

My fault, I did't ask the question very clear. In different environments which use different endian representation, it is clear, this function will keep the data in a same meaning, but under the same endian representation, what does it means?

It absolutely will change the meaning of the data, or there is some other reason to swap it?

Answer Source

In the pseudocode for SHA256 on wikipedia it says

Pre-processing: append the bit '1' to the message append k bits '0', where k is the minimum number >= 0 such that the resulting message length (modulo 512 in bits) is 448.

append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer(this will make the entire post-processed length a multiple of 512 bits)

x86/x86_64 Linux and Unix are small endian.

It's converting the length of the message to big endian to add it to the end of the message, which it does in the source at L105 of sha256.c, and that section of the code is the only place where the `swapE64`

function is called:

https://github.com/noryb009/sha256/blob/77a185c837417ea3fc502289215738766a8f8046/sha256.c#L100