r/C_Programming • u/ProgrammingQuestio • Aug 12 '26
When exactly does endianness conversion happen?
For example if I have uint8_t arr[] = {192, 94}; since these are individual bytes, they get stored in memory as they appear in the code: 0xc0, 0x5e, right?
But if I were then to grab these two bytes as if they were a single uint16_t:
uint16_t *val = (uint16_t*)arr; then these bytes would be parsed (??), on a little endian system, from memory as if they're LSB followed by MSB, meaning they'd essentially be "flipped" and read as 0x5ec0. Correct?
So it seems that the "conversion" or "flip" happens when reading from memory?
But what if I'm actually storing a uint16_t then reading it as individual bytes? It seems this gets stored in "flipped" order (in memory as 0xc0, 0x5e) because when I parse those two bytes as uint8_t, it gives me it in this "flipped" order.
65
u/lfdfq Aug 12 '26
No parsing happens. It's not like on one endianness system it has to flip the bytes around. It's just a difference of interpretation of the same bytes.
3
u/Sumandora Aug 12 '26
There is no conversion, when dereferencing a integer pointer then you get a different value. If you write an integer in your program it is stored in the binary given the targeted endianness. So when you read a uint16_t using a byte array then you get different answers depending on the endianness, however this is not because the CPU changed anything, it is just how the CPU sees the values. So you could say that the compiler flipped them in some regard, however when the compiler ran on the same target (e.g. you are not cross compiling) then there is no flipping necessary. Instead of thinking about "parsing" or "converting", just consider your CPU a right-to-left/left-to-right reader, after all you wouldn't say that arabs convert the text from right-to-left into left-to-right in their head, they just read it backwards as is.
22
u/adamentmeat Aug 12 '26
The conversion happens when the CPU accesses the memory with a specific command. Let's just imagine a RISC CPU for simplicity. This won't be 100% accurate because I am trying to explain it simply and in general terms.
When you assign the memory of
arrto 0xc05e, it will likely be two "store byte" commands (compiler or code can optimize this but it is transparent). Then, when you access the memory at arr as a uint16_t on a 32 bit system, it will use something like "load half-word". This will result in the bytes being flipped on a little endian system.If you do "store half-word" with 0xc05e, it will result in the bytes being flipped.
It is the CPU itself that does this based on its architecture.
6
u/julia_flat Aug 12 '26
Endianness is about how data is stored in memory, so the “conversion” happens when reading / writing memory. If I wrote 0xABCD to address 100 in a big endian system, 0xAB would be at address 100 and 0xCD would be at address 101. Similarly, if I wrote 0xABCD at address 100 in a little endian system, 0xCD would be at address 100, and 0xAB would be at address 101.
3
u/CounterSilly3999 Aug 12 '26 edited Aug 13 '26
0x5ec0 is still not flipped. In
lowlittle endian machine bytes are stored lower to higher, in positional system digit positions of numbers are written from right to left, the order remains intact.3
u/moocat Aug 13 '26
Endianness matters when you are serializing to external format. Let's say you want to write a
uint32_tto a disk file as the underlying 4 bytes. You then want to read that file on a different computer. If the other computer has a different endianness the numeric value will be wrong.To handle this correctly, you would want to convert the endianness when you write and/or when you read the file. You would also do something similar if you were reading or writing the data over a network connection.
4
u/FitMatch7966 Aug 12 '26 edited Aug 12 '26
Not sure where the confusion is. When you write 0x5ec0 that’s a language notation, but it doesn’t mean they are stored in memory or registers in that order, ever. So no flip.
A little endian system is built so that a word operation in the CPU expects the bytes in that order. The compiler generates them in that order. The functions that read or convert integers pack them that way. They are never not in that order except if written to a binary file. If you want a binary compatible file format, you need to implement the byte swapping yourself in the file reader/writer.
2
u/flatfinger Aug 12 '26
While most modern systems have caches that complicate things, a typical 32-bit microcomputer without cache will have a set of 30 address lines that identify a byte in each of four banks of memory and indicate whether the processor wants to do a read or write. Each bank of memory will have a set of 8 data bus wires and a control wire that indicates whether the processor wants to do anything with that bank.
To perform a 32-bit read, the CPU will indicate it wants to do a read of the address specified by the top 30 address bits, activate all four banks, and observe the contents of all 32 data bits.
To perform a 32-bit write, the CPU will indicate that it wants to do a write of the address specified by the top 30 address bits, put the desired data on all 32 data bits, and activate all four banks.
To perform an 8-bit read, the CPU will indicate that it wants to do a read, activate one bank of memory based upon the bottom two address bits, and observe what's on one of the eight sets of data wires.
To perform an 8-bit write, the CPU will indicate that it wants to do a write, put the desired data on all four sets of 8 data wires, and activate one bank of memory based upon the bottom two address bits (the CPU wouldn't have to output data on the buses associated with the inactive banks, but inactive banks will ignore any data from the CPU and outputting data on both banks is simpler than only feeding it to one).
Endianness is determined by the mapping between bit patterns in the bottom two address bits, and bank selection. If a bit pattern of 00 selects the bank that would hold the least significant eight bits, the system is little-endian. If 11 would select that bank, the system is big-endian.
2
u/rubidus-api Aug 12 '26
Endianness is not an operation that “flips” bytes at some particular point. It is the convention that defines how the bytes of a multi-byte integer value are represented in memory.
In other words, the machine does not normally store some neutral byte sequence and then reverse it while loading, or vice versa. A store maps an integer value to its byte representation according to the machine’s byte order, and a load maps that byte representation back to an integer value according to the same rule.
I suspect that thinking of this as “reading the bytes backwards” or “writing them backwards” may be causing the confusion. That wording can suggest that an actual reversal happens in the middle, or even that the bytes might be reversed twice. Normally, no such conversion step occurs.
Regarding this question:
The important question is: which uint16_t value are you storing? The resulting byte sequence depends on that value and on the machine’s byte order.
For example, on a little-endian system:
Conversely:
If the stored value is 0xc05e, the representation is different:
Therefore, it is not that the bytes are “flipped when read” or “flipped when written.” The bytes in memory are simply the little-endian representation of the stored integer value.
Also, this should not be done by casting the array:
Dereferencing that pointer may have undefined behavior because arr may not satisfy the alignment requirement of uint16_t, and the access may violate C’s effective-type and aliasing rules. memcpy is the portable way to copy the object into a uint16_t.
2
u/WittyStick Aug 12 '26 edited Aug 13 '26
You shouldn't really do
(uint16_t*)arrwherearris auint8_t*. This is called a "strict aliasing violation," and while C compilers usually permit it, they will warn or produce errors if you have the right compiler flags set-Wall -Werror -Wpedanticetc.The reason it's discouraged is because it is unportable - it will produce different results on a big-endian and little-endian machine (there are even machines that are neither big nor little endian also).
You should not need to concern yourself with how the machine stores data internally - generally, you should only care about endianness when you have a specific file format, or protocol to serialize to, where the endianness is part of the specification of that protocol.
To serialize a
uint16_tto a little endian protocol, you do the following.To serialize to a big endian protocol, you switch these two bytes.
To deserialize from a little endian protocol, do the following:
To deserialize from a big endian protocol:
These snippets will work no matter what the host endianness is. It does not matter if the host is big or little endian - they will both achieve the correct result. What matters is the source/target format which you are reading/writing.
You will see a lot of bad code where the programmer tries to test what the machine's endianness is before converting to/from some format. These programmers are almost always doing the wrong thing - they think they're getting some performance gains by not performing shift and bitwise operations like above, but instead just casting with the strict aliasing violation. What they don't realize is that compilers are smart enough to detect these patterns, and writing to a little endian format on a little endian machine may end up being a no-op when compiled. If conversion is required, the compiler knows what the endianness of the machine is and may convert all these shifts and bitwise operations to a single
bswapoperation. There's no need to try and be smart - just write the portable conversion routines as above and let the compiler be smarter than you.See in Godbolt - if you look at the assembly emitted for each function, you will see there are no shifts and bitwise and/or - just
movfor little endian, andbswapandrolfor little->big endian conversion. The compiler in this case knows it is running on a little endian machine, and will swap the bytes. A compiler running on a big-endian machine would do the opposite - swap the bytes for writing little endian. We didn't need to test what the endianness of the machine is - it is almost never necessary to do so (unless you are implementing the compiler).2
u/Vincenzo__ Aug 12 '26
The bytes in memory stay in the same order, c0 at the lower address and 5e at the higher address. The difference is that when a little endian cpu loads that and tries to do math with it c0 5e is the number 0x5ec0, while a big endian cpu will interpret that as 0xc05e. There is no inversion happening in memory at all, the bytes stay like that, it's just that the CPU is wired differently. The CPU doesn't need to put the number in the human order to be able to do math with it
2
u/Recycled5000 Aug 13 '26 edited Aug 13 '26
Endian is a mathematical relationship between, here, two consecutive bytes, as chosen by the (designers of the) processor. (Yes, sometimes switchable on some processors.)
The formula is i16 = b[0] + b[1] * 256, where b is the lower address of a two byte item, for little endian.
The formula applies whenever the processor reads or writes a two byte item in a single operation involving a 16 bit value.
—
The term parsing is usually reserved for recognizing patterns (like sentences) as meaningful constructs defined by a language that has choices, for example to interpret 4+5*6 (using the expected operator precedence); that requires parsing.
While there are some similarities, applying a formula doesn’t seem to rise to the level of parsing, of recognition.
3
u/aocregacc Aug 12 '26
I mean if the bytes get "flipped" when reading a uint16, you have to "flip" them again when you write the uint16 back to memory, otherwise you would have changed the order in memory and you'd get a different value when you read the uint16 the next time.
1
u/gizahnl Aug 12 '26
You're correct on both counts, it all happens in memory.
Though no parsing or flipping is involved, it's just how it operates on it.
It could be possible that the register itself doesn't have the same endianess ass the memory, on which case the load instruction would need to do the byte swapping.
1
u/Blitzbasher Aug 12 '26
There is no conversion. Think of an array like a linked list that is physically stored next to each other in order. For an array the order matters because it doesn't make sense to increment through an array by decrementing a reference pointer.
Any number larger than a byte must be stored across multiple byte chunks and the cpu architecture simply chooses what order to do this in.
1
u/Luftzug-oder Aug 12 '26 edited Aug 12 '26
i don't get what you're saying?
if you have arr[] pointing to 8 and 9, for example, they would be stored as 00001000 and 00001001 in memory. so when you read them as a uint16_t, it reads the first and only byte of 9 (because the order reverses bytes, not bits - which you seem to get) - 00001001 - and then of 8 - 00001000. so you get 0000100100001000, or 2312
there is no flip. i think maybe you are confused because you are comparing the behaviour between a numeral where there is only 1 byte, so no reversed order, and 2 bytes, where it is stored 'differently'
1
u/sciencekm Aug 12 '26
CPUs have a component called Load/Store Unit which (as the name implies) is responsible for reading and writing bytes from memory. It maps the memory byte sequence with the register byte sequence, reversing them if needed.
I say "if needed" because the CPU may already be in a "mode" where the register byte sequence is the same as the memory byte sequence. This is for CPUs where the register byte sequence can be set to either big or small endian (aka bi-endian CPUs).
1
u/TPIRocks Aug 12 '26 edited Aug 12 '26
It happens at the hardware level when multibyte load or store operations are happening. Since this is how it's stored in computer RAM, multibyte data in structures will also be laid out accordingly. Little endian: LSB is stored at the lowest address, big endian is the opposite with the MSB occupying the lowest memory address.
Big endian may seem. More intuitive, especially if you're visualizing RAM from left to right, with the lower addresses to the left. The number will span the bytes from left to right. Despite all that, little endian processing is more common.
But to answer your question directly, "conversion" happens when you call hton() on a little endian system, and it rearranges the byte order. TCP/IP uses big endian, in network frames.
1
u/EmbedSoftwareEng Aug 12 '26
Endianness is about byte ordering in multi-byte values. When you have an array of bytes, then you'll still have the same array of bytes when it gets communicated to a machine of a different endianness. Pointer variables in C are going to store their bits in whatever way is most convenient for the architecture in question, and honestly, there's no reason to concern yourself with those details any further, unless you're trying to write an emulator, which would care about such details. When you're just data marshalling with structures like linked lists, those details abjectly don't matter.
Now, when you have complex data structures that span more than one byte, then you might start getting into endianness territory. For instance, if you wanted to communicate a single float value, you would need to be careful to byte order it in a specific sequence, generally network endianness (big-endian) for communication across a network or other media, and then the device on the other end can re-order those bytes from network endianness to its own local endianness as it sees fit to insure that the IEEE floating point value data format winds up in memory correctly for the local architecture.
When doing such byte reordering is when you need to concern yourself with how the local machine architecture orders multibyte data in memory. When just doing:
You honestly don't care how those two bytes make their way from memory cells out there in RAM to bits in a CPU register. You just want them to be coherent when the CPU subsequently operates on them.
When you have that pointer to the data in memory, you can always get at the individual bytes in ascending memory address values by doing:
If you're on a big-endian machine, this will print the bytes in the order depicted, "1234". If you're on a little-endian machine, the bytes will be swapped to "3412".
In the embedded world I live in, on-die peripheral silicon will often implement registers that hold 32-bit values to aid device driver software in determining if they need to byte-swap in and out of the periipheral. If the driver reads the register as 0x12345678, then the peripheral's endianness is the same as the machine's own architecture. If it reads as 0x78563412, then all I/O on multi-byte registers have to be byte-swapped in order for the peripheral to work correctly with the CPU.
Memory is functionally word-oriented, but memory architectures usually offer break downs that allow for half-word and byte-oriented accesses. What it really amounts to is that when a sub-word access is requested, the whole word is transferred across the memory bus, but only the selected sub-word portion is not masked off and conveyed to the destination register. When I do
uint32_t n_value = 0x12344567;on a 32-bit machine, the whole value is on the memory data bus at once. On a 64-bit machine, it'll only occupy the upper or lower 32 bits of the data bus, and at the destination memory cells, the half that's not used is masked off so the write doesn't change the bytes are are not involved in storing n_value. On a 16-bit architecture, the compiler will have marshalled the memory write into two separate writes for the two 16-bit words and half of the value is on the bus at a time, and each write is to a different 16-bit address so the value is depositted in the architecture-correct order.1
u/strange-the-quark Aug 12 '26 edited Aug 13 '26
If you have a string of bytes ABCDEF (I'm not using hex notation here, just a letter to represent each byte), and you just read them as individual bytes, then you just get, A, B, C, D, E, F.
But if you have a multi-byte data structure, then you can choose which byte (or which end) you'll store first. E.g., kind of like you can write down a date in different ways: DD/MM/YY, or YY/MM/DD, or MM/DD/YY. It's a convention. It's all conceptually the same date.
So if your multi-byte data structure is conceptually represented by AB, where A is considered in some sense the most significant byte (its choice affects the value the most), you can store it either as AB, or BA in memory, depending on the convention the system uses.
Then when it reads it back, it'll just assume that the string of bytes follow the convention of the system, and it will read in your data structures that way. So if ABCDEF is read by a system that uses the opposite endianness, it will interpret it conceptually as BA, DC, FE, as in, you'll get whichever data values are represented by those particular sequences. There's no parsing, no conversion, it just assumes it's in the format it wants.
If you use an int in a programming language, or if you read a sequence of bytes as an int, you just get an int, the bit shift operators <<, >> work as expected, and you have no idea about the actual ordering of the bytes in the memory - the language rules are organized around an endianness-independent conceptual representation. But if you read the same data as individual bytes, you might get a surprise.
Now, some networking software may do endianness conversion in order to interoperate with other systems. Also, some file formats specify a particular endianness (e.g. various image formats; the image editing software must then ensure the spec when saving the file regardless of the endianness of the host system).
1
u/ReallyEvilRob Aug 12 '26 edited Aug 12 '26
There is no conversion happening at all. The only thing going on is interpretation. The bytes are stored in the order you place them in memory, so arr[0]=192 (0xC0) and arr[1]=94 (0x5E). On a little endian system *(uint16_t *)arr=Ox5EC0 (24256). On a big endian system it would be 0xC05E (49246). Nothing is being converted. It's all just the way memory is being interpreted. Any conversion that happens would be when the output is formatted for display, ie. binary to ASCII.
You could force a byte flip, which is actually necessary when programming with sockets. Network byte order is always expected to be big endian regardless of the machine architecture you're targeting. If hostOrder is a uint16_t, before you send it over the wire, you always have to call
uint16_t netOrder = htons(hostOrder);On a little endian system, the bytes in netOrder will be reversed from hostOrder. On a big endian system, htons() will return the bytes as is.1
u/Longjumping_Cap_3673 Aug 12 '26 edited Aug 12 '26
Numbers don't have endianness; some representations of numbers do. There's no endian conversion happening when you read a uint16_t from an array of uint8_t.
The CPU assumes the bytes in the uint8_t array are a little-endian representation of a number, and it decodes the bytes into that number. At a low-level, that number is stored in a CPU register, which represents the whole number atomically (well, CPU registers are not byte-addressable, at least), so there is no concept of endianness. There is no first byte or second byte; there is only the full number.
And yet there is actually an endianianess conversion in your example. It happens when you print the number. Numbers are conventionally writen from most-significant digit to least-significant, so the number printing function has an algrithm to encode a number into a big-endian representation. The decode and encode sequence together forms an endianness conversion (and only together). I think maybe the big-endian representation of written numbers is contributing to your confusion.
1
u/Irverter Aug 13 '26
It gets flipped when printing it to the user.
"0x5ec0" is independent of the endianess of the computer. We write it big endian and read it big endian. It doesn't change how the computer stores it, the lowest byte is c0 and the highest byte is 5e, and it will be stored in memory corresponding to the cpu endianess.
1
u/fdwr Aug 13 '26
It's unrelated to the language (C, assembly, ...) but rather the hardware. So you could ask the same question for assembly (e.g. x86
mov edx, [ebp+4]vs MIPSlw $t0, 8($s1)), which is the same answer for C.For a 16-bit word, on LE8 machines, bits 0-7 and bits 8-15 from memory become bits 0-7 and bits 8-15 of the loaded register, whereas on BE8 machines, bits 0-7 and bits 8-15 from memory become bits 8-15 and bits 0-7 of the loaded register, meaning the circuitry is what flips them. There have been some weirder cases too, like BE16 on the PDP-16 where bits 0-15 and 16-32 become register bits 16-32 and 0-15 (basically each 16-bit word is swapped), or the Zapit GameWave where the entire 32-bit word was swapped even when you read 16-bits (meaning the first 16-bit word actually started at byte offset 2), or older ARM chips BE-32 mode where 32-bit word reads were actually identical to LE8 reads whereas 16-bit reads were read as if there was a
trueAddress = givenAddress ^ 3being applied (where again the first 16-bit field actually started at byte offset 2).1
u/mykesx Aug 13 '26
CPUs load registers from memory and store them to memory. For a 2 byte word, it can store low byte then high byte or high byte then low byte. The byte order determines the endianness.
Any language, interpreted or compiled, must use registers at some level to deal with memory, math, and logic operations.
1
u/CreepyWritingPrompt Aug 13 '26
It's at the reading, yup. If an program wants to add 2 16 bit numbers, it may start by loading one of them into a register. Whether the first byte goes into the bottom or the top of the register is dictated by the endianness of the cpu. In memory, it's just bytes until they are read.
When the result needs to be stored back into memory, those two bytes will be stored in the endianness-dictated order.
If an operation is happening directly on something in memory, rather than via a logical register, the electronics of the processor will still load the bytes up in some order before feeding the whole thing into the operation-doing electronics.
1
u/Orkiin Aug 16 '26
In most case memory is read and written in little endiang because is easier for computers to store data like that, say for example you have an int with value 1 and you want to cast it as an uint8_t if memory is stored form less significant value then you would have in memory stored 0x01 0x00 0x00 0x00 and as you can see the first value is 1 therefore the address for uint8_t and int is the same and you can read either 4 bytes or 1 byte according to the type that you want, that way you can store the data from the beginning of the memory to the end and always read the correct value without too much work, otherwise the address af the memory should be referred as the most significant value instead and it would make more sense then to treat the begging of the memory like the end and the end like the beginning. Also it makes more sense to treat it that way because if for exampe you have an array of bytes you would need to index it to the last bye in order to get the value of an int that is less than 256. Also if you wanted to allocate memory, it makes more sense to store data from the point where it is pointing that going from end to beginning. This is all my interpretation and I may have some erroneous assumptions, but I tried to explain it the way I understood it
1
u/TituxDev Aug 16 '26
In one of my C projects I have a binary file format where I chose little-endian as the standard byte order for the file, regardless of the host architecture.
My serialization/deserialization code explicitly handles the case where the native architecture is big-endian. When reading a multi-byte value, it swaps the bytes as necessary before storing the resulting value in the corresponding struct field.
So the file representation is independent of the CPU's native endianness.
For example, if the file contains a "uint32_t" as:
"78 56 34 12"
that represents "0x12345678" in my file format. On a little-endian host, no conversion is necessary. On a big-endian host, the bytes have to be reordered before the value is placed into the struct.
That was one of the practical reasons I ended up having to understand endianness properly: it becomes important as soon as you define a portable binary file format.
You can watch how it works in the file ntfile.c https://github.com/TituxDev/NeuroTIC