The code snippet contains two functions, `buildIntLittleEndian` and `buildIntBigEndian`, that...
August 23, 2025 at 04:20 AM
The code snippet contains two functions, buildIntLittleEndian
and buildIntBigEndian
, that construct a 4-byte int
(assuming int
is 4 bytes on the platform) from a char
array input
using either little-endian or big-endian encoding. Here's what each function does in detail:
1. buildIntLittleEndian
This function interprets a sequence of bytes in little-endian order and constructs an integer from them.
int buildIntLittleEndian(const char *input) {
int res = 0;
for (int i = 0; i < sizeof(res); ++i) {
res |= input[i] << (8 * i);
}
return res;
}
-
How it works:
res
is initialized to0
.- A
for
loop iterates over each byte of the 4-byteint
(or however many bytessizeof(res)
indicates, typically 4). - In each iteration:
- The function takes the
i
-th byte ofinput
(input[i]
). - Shifts it left by
8 * i
bits to move it into the correct position for the little-endian layout. - Combines it into the result
res
using a bitwise OR operation (|
).
- The function takes the
- The first byte (
input[0]
) is placed in the least significant byte ofres
, the second byte in the next least significant byte, and so on, consistent with the little-endian order.
-
What it does:
- Constructs an integer by treating the input bytes as if they are stored in little-endian format: least significant byte first.
2. buildIntBigEndian
This function interprets a sequence of bytes in big-endian order and constructs an integer from them.
int buildIntBigEndian(const char *input) {
int res = 0;
for (int i = 0; i < sizeof(res); ++i) {
res <<= 8;
res |= input[i];
}
return res;
}
-
How it works:
res
is initialized to0
.- A
for
loop iterates over each byte of the 4-byteint
. - In each iteration:
- The function shifts the existing bits of
res
left by 8 bits (res <<= 8
) to make room for the next byte. - Combines the current byte (
input[i]
) intores
using a bitwise OR operation (|
).
- The function shifts the existing bits of
- The first byte (
input[0]
) is placed in the most significant byte ofres
, the second byte in the next most significant byte, and so on, consistent with the big-endian order.
-
What it does:
- Constructs an integer by treating the input bytes as if they are stored in big-endian format: most significant byte first.
Summary:
-
buildIntLittleEndian
:- Converts the byte sequence in the input into an integer assuming the bytes are in little-endian order.
- Example: If
input = {0x01, 0x02, 0x03, 0x04}
, the result is0x04030201
.
-
buildIntBigEndian
:- Converts the byte sequence in the input into an integer assuming the bytes are in big-endian order.
- Example: If
input = {0x01, 0x02, 0x03, 0x04}
, the result is0x01020304
.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node