I am trying to swap bytes in c.
I am suppose to swap the nth byte and the mth byte. I am given examples such as 0x12345678, 1, 3) = 0x56341278. 1 meaning n and 3 meaning m. I am suppose to use these operators to find a formula to swap these ! ~ & ~ ^ | + << >> i am allowed to use max 25 operators. I know this is not actually coding but i don't know where else to ask... Would be great if anyone could help me out in finding this out.
the intel cpu has a built in operation to do this for endian reversal purposes; I think the command is 'bswap'. If you want to do a lot of them fast. (yes, I know its not in the assignment).
you can also brute force cast into unsigned char *s and swap them with the standard swap operations..
true. you do need to know what you are working with when doing bit level code. This was for standard 1 byte chars against 8+ byte ints. The order of the bytes in memory of the integer is irrelevant to swapping them around. It will matter when trying to USE the data after manipulations though.
The endianness is relevant, because OP needs to swap the nth and mth bytes of the integer, not just reverse the bytes of the integer. The result of your snippet is undefined, but the result of this isn't:
1 2 3 4 5
std::uint32_t n = 0x12345678;
std::uint8_t a = (n >> 8) & 0xFF;
std::uint8_t b = (n >> 24) & 0xFF;
n &= 0x00FF00FF;
n |= (b << 24) | (a << 8);
If you want to do something equivalent with direct memory accesses you'll need to know the endianness of the underlying platform.
I see. You are saying the nth byte in terms of human readable most significant is left format. I was saying the nth byte is from memory location zero. That is why you think the endian matters, and I don't. Makes perfect sense.