中文   |    

How Do You Handle Byte-Order (LSB vs. MSB First) in Page-Mode Writes?

Table of Contents

Visually illustrates the difference between big-endian and little-endian storage of a 16-bit value (0x1234) in memory, showing how bytes are arranged (12 34 for big-endian, 34 12 for little-endian)
Visually illustrates the difference between big-endian and little-endian storage of a 16-bit value (0x1234) in memory, showing how bytes are arranged (12 34 for big-endian, 34 12 for little-endian)

To handle byte-order in page-mode writes, you must match the device’s endianness and bit-order. This ensures each byte or bit is written in the way the memory or display expects. Start by checking if the device reads LSB-first or MSB-first data.

When your system and the device use different orders, reverse the bytes or bits before sending. Use simple code functions or hardware settings where possible. If the hardware doesn’t allow changes, apply bit-level manipulation in software.

Page-mode writes must also follow memory constraints. Align the data block to the page size and start address. Avoid crossing page boundaries without restarting the write cycle. This helps keep the data correct and complete.

These steps work together. You organize data for the page, then arrange it by bit and byte order. If you miss any part, the result may be unreadable or ignored by the device.

What Are the Fundamentals of Byte Ordering (Endianness)?

3.97 inch TFT LCD Module - 040HT014
3.97 inch TFT LCD Module - HUA XIAN JING

Byte ordering, or endianness, is how computers arrange bytes in memory for multi-byte data like integers. There are two types: big-endian and little-endian. In big-endian, the most significant byte (MSB) comes first. In little-endian, the least significant byte (LSB) comes first. This difference affects how systems store and read data. It can cause issues when devices or programs use different endianness, making it a key concept for anyone working with computers or networks.

This matters in real projects. For instance, x86 processors, found in many computers, use little-endian. Network protocols, like those for the internet, often use big-endian. I once worked on a project where data from a sensor (big-endian) was misread by a little-endian processor until we swapped the bytes. Knowing endianness helps you avoid these mix-ups and ensures data moves smoothly between systems.

Here’s a quick look at the difference:

  • Big-endian: Stores 0x12345678 as 12 34 56 78.
  • Little-endian: Stores 0x12345678 as 78 56 34 12.

Think of it like reading a number: big-endian goes left to right, while little-endian goes right to left.

What Is Byte Order?

Byte order, also called endianness, is the way bytes are placed in memory for multi-byte values. In big-endian, the most significant byte (MSB) goes to the lowest memory address. In little-endian, the least significant byte (LSB) goes first. This choice changes how data looks in memory and can lead to errors if not handled right.

Take a 32-bit number like 0x12345678. In a big-endian system, it’s stored as 12 34 56 78 across four memory addresses. In a little-endian system, it’s 78 56 34 12. I’ve seen this cause headaches in embedded projects—like when a device sent data in big-endian, but the software expected little-endian. Checking the byte order saved the day.

Here’s the layout:

  • Big-endian:
    • Address 0: 0x12
    • Address 1: 0x34
    • Address 2: 0x56
    • Address 3: 0x78
  • • Little-endian:
    • Address 0: 0x78
    • Address 1: 0x56
    • Address 2: 0x34
    • Address 3: 0x12

Imagine memory as a row of boxes. Big-endian fills them from the big end; little-endian starts with the small end.

How Do You Determine and Match Endianness?

You need to know a system’s endianness to work with its data correctly. Check the system architecture details in its device datasheet or run a test with code. This prevents mistakes when connecting devices or sending data across networks.

In one project, I had to figure out a device’s endianness. The datasheet wasn’t clear, so I wrote a quick test. I stored a number like 0x12345678 and checked the first byte in memory. If it was 0x78, the system was little-endian; if 0x12, it was big-endian. Here’s a simple C example:

				
					#include <stdio.h>

int main() {
    union {
        unsigned int num;
        unsigned char bytes[4];
    } test;
    test.num = 0x12345678;
    if (test.bytes[0] == 0x78) {
        printf("Little-endian\n");
    } else if (test.bytes[0] == 0x12) {
        printf("Big-endian\n");
    }
    return 0;
}
				
			

If endianness doesn’t match, use byte-swapping. For example, to flip 0x12345678 to 0x78563412, you can write a function like this:

				
					unsigned int swap_bytes(unsigned int x) {
    return ((x & 0xff000000) >> 24) |
           ((x & 0x00ff0000) >> 8) |
           ((x & 0x0000ff00) << 8) |
           ((x & 0x000000ff) << 24);
}
				
			

This swaps the bytes to match the other system’s order.

What Is Bit Ordering (Serialization) in Communication Protocols?

240x128 Monochrome COB Graphic LCD Module - 240128B
240x128 COB Graphic LCD Module - HUA XIAN JING

Bit ordering, or serialization order, defines how bits are arranged and transmitted over communication lines. There are two common formats: MSB-first (Most Significant Bit first) and LSB-first (Least Significant Bit first). The order determines whether the highest or lowest value bit is transmitted first. Different protocols follow different bit ordering rules. For example, SPI usually transmits MSB-firstI2C also uses MSB-first, while some UART implementations may vary or be configurable.

Incorrect handling of bit order leads to misinterpreted commandsdata corruption, and communication breakdown, especially in embedded LCD systems and sensor interfacing.

Bit Ordering Across Communication Protocols

ProtocolDefault Bit OrderConfigurability
SPIMSB-firstSome controllers allow LSB-first
I2CMSB-firstGenerally fixed
UARTOften LSB-firstDepends on implementation

What Is Bit Order?

Bit order refers to the sequence of bit transmission in a byte. In MSB-first transmission, the most significant bit is sent first. In LSB-first, the least significant bit goes first. For an 8-bit value 0b10110010, MSB-first sends 1 first, while LSB-first sends 0 first.

Protocols are designed with a default order. For example, SPI’s MSB-first format aligns with most memory and register maps. In UART, some systems default to LSB-first, where the lowest-value bit leads.

In a display module using SPI communication, failing to follow the correct bit order results in distorted colorsmisread commands, or incomplete frames.

Bit Order Visualization: MSB vs. LSB Transmission

				
					Byte: 0b11001001
MSB-first: 1 -> 1 -> 0 -> 0 -> 1 -> 0 -> 0 -> 1
LSB-first: 1 -> 0 -> 0 -> 1 -> 0 -> 0 -> 1 -> 1
				
			

How Can You Reverse Bit Order?

Reversing bit order is essential when interfacing two systems with mismatched transmission formats. You can achieve this through bit-reversal algorithms in software or by configuring hardware registers in some microcontrollers.

Bit-Reversal in C

				
					unsigned char reverseBits(unsigned char b) {
    b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
    b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
    b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
    return b;
}
				
			

This function flips the bits from MSB to LSB or vice versa. It is useful when the peripheral expects a different bit order.

For performance-critical systems, reversing bits in hardware is faster. Many MCUs with SPI or UART modules include control registers to set the bit order automatically.

Software vs. Hardware Bit Reversal

MethodUse CaseProsCons
SoftwareCross-platform, portableFlexible, simple to debugCPU overhead, slower
HardwareHigh-speed communication, MCU-specificFast, efficientRequires supported hardware

Why Does Bit Order Matter in Embedded LCD Systems?

Bit order directly affects how an LCD controller interprets data(What is an LCD controller board?). For example, if the controller expects MSB-first and receives LSB-first, the command will be misread, potentially causing no displayincorrect characters, or color errors.

In embedded LCD systems using UART or SPI, always consult the datasheet. Some allow bit order settings, others require you to reverse bits manually before transmission.

LCD System Configuration: Bit Order Matching

Interface TypeTypical Bit OrderAdjustment Method
SPIMSB-firstSPI control register
UARTLSB-firstCode-based bit reversal
I2CMSB-firstFixed, match in software

How Can You Structure Page-Mode Writes with Correct Ordering?

Page-mode writing requires organizing data to match the page size and bit/byte order of memory devices like EEPROMs or flash. Data must be written with proper alignment, meaning both start address and data block length should fit within the defined page size. Additionally, in systems where multi-byte values are used, their endianness must match the storage or communication expectations, or the values will be misread or corrupted.

When page-mode write operations ignore correct ordering, the result may include overwritten bytesincomplete transactions, or garbled output. Systems interfacing with LCD modulessensor buffers, or embedded storage often rely on strict data and byte alignment, especially when operating over I2C or SPI buses.

Aligned Write Table: Page Size vs. Start Address

Page SizeAligned AddressMisaligned Example Result
64 bytes0x0000, 0x00400x0021 Write spills across pages
128 bytes0x0100, 0x01800x0111 Extra write cycles required

What Is Data Organization in Pages?

Memory devices typically organize storage in fixed-size pages, such as 32, 64, or 128 bytes. Page-mode write operations must begin at the start of a page and should not cross a page boundary without a new write cycle. Writing across boundaries leads to partial writes or data corruption.

To ensure consistent behavior, developers align the start address to the page boundary and pad or trim the data to match the page size. For instance, writing 48 bytes starting at address 0x0020 on a 64-byte page results in an overflow into the next page, unless handled carefully.

In LCD modules or EEPROM configurations, this level of control ensures correct frame updatesfont storage, or image rendering.

Byte and Bit Considerations for Page Writing

ConditionAlignment RequiredNotes
Single-byte writesNoSafer, slower for bulk updates
Multi-byte valuesYesWatch for endianness mismatches
Structured arraysYesAlign to both element and page size

What Happens in a Real EEPROM Page Write Example?

Let’s walk through a 64-byte EEPROM using SPI for a full-page write. The key is ensuring proper alignment and byte ordering for multi-byte data like uint16_t or uint32_t values.

  1. Start at aligned address: e.g., 0x0080 (64-byte boundary)
  2. Organize data block: Ensure data fits in 64 bytes. Group multi-byte values.
  3. Convert endianness: If needed, reverse byte order to match EEPROM expectations.
  4. Initiate SPI transfer: Use CS (Chip Select), then send instruction, address, and data.
  5. Wait for write cycle: Monitor status register or delay as needed.

Example Write Code (C-style Pseudocode)

				
					void writeEEPROMPage(uint16_t startAddr, uint8_t* data) {
    selectEEPROM(); // Activate CS
    sendByte(WRITE_COMMAND);
    sendByte((startAddr >> 8) & 0xFF); // MSB of address
    sendByte(startAddr & 0xFF);        // LSB of address
    for (int i = 0; i < 64; i++) {
        sendByte(data[i]); // Byte order must match EEPROM's expectation
    }
    deselectEEPROM();
    waitForWriteCycle();
}
				
			

If the EEPROM is MSB-first and your system is LSB-first, reverse the byte order before calling sendByte().

Bit/Byte Handling Chart

Data TypeSystem EndianEEPROM ExpectationAction Needed
uint16_tLSB-firstMSB-firstReverse before write
uint32_tMSB-firstMSB-firstNo change
Custom CmdMixedDefined by deviceConsult datasheet

How to Handle Multi-Byte Values with Different Endianness?

When writing structures or buffers containing multi-byte data, you must detect whether the memory device stores bytes in MSB-first or LSB-first order. Mismatches cause data to appear reversed or corrupted.

Use utility functions to convert byte order before writing. Alternatively, some systems provide compiler macros or intrinsics for endian conversion.

Reversing uint16_t for MSB-first EEPROM

				
					uint16_t val = 0x1234;
uint8_t hi = (val >> 8) & 0xFF;
uint8_t lo = val & 0xFF;
sendByte(hi); // Send MSB first
sendByte(lo); // Then LSB
				
			

Endian Conversion Reference Table

Input FormatTarget FormatConversion Required Tool
LSB-firstMSB-firstYes Bitwise operations
MSB-firstLSB-firstYes Manual or built-in API
Native MatchNative MatchNo Direct transfer

How Can You Configure Communication Protocols for Correct Byte/Bit Order?

To ensure accurate data transmission, communication protocols must be configured with the correct byte and bit order. Many protocols, like SPII2C, and UART, offer options to set bit transmission order (e.g., MSB-first or LSB-first) and expect data in specific byte orders depending on the connected device. If hardware allows it, these settings are done using registers or driver functions such as SPI.setBitOrder() in platforms like Arduino. When hardware doesn’t allow this adjustment, you must rely on software-level byte or bit reversal before transmission(How Should You Drive Backlight in an Embedded LCD Display?).

Incorrect configuration results in inverted commandsgarbled values, or LCD misbehavior in embedded systems. Understanding both protocol capabilities and device expectations is key.

Byte/Bit Order Support Across Protocols

ProtocolBit Order ConfigurableByte Order AffectedCommon Setting
SPIYes (e.g., setBitOrder)Yes (handled in software)MSB-first
I2CNoYes (manual packing)MSB-first
UARTRarelyYes (handled manually)LSB-first or variable

What Are SPI, I2C, and UART Protocol Settings?

SPI allows bit order configuration, typically through functions like SPI.setBitOrder(MSBFIRST) on platforms like Arduino or by modifying control registers directly on microcontrollers. This sets whether the most or least significant bit is transmitted first. Devices like LCD modulesEEPROMs, or flash chips may require a specific setting.

I2C usually follows MSB-first transmission, and its bit order is not adjustable. Data arrangement must be handled in software. UART protocols differ—some send LSB-first, and most do not allow bit order configuration. Instead, you need to manage byte composition before writing.

SPI Bit Order Configuration in Arduino

				
					SPI.begin();
SPI.setBitOrder(MSBFIRST); // or LSBFIRST
SPI.transfer(myByte);
				
			

This ensures that the SPI hardware sends bits in the correct sequence to match the peripheral’s expectations.

Protocol Configuration Summary Table

PlatformConfiguration MethodAffected Order Tools/Functions
Arduino (SPI)SPI.setBitOrder()Bit order SPI library
STM32 (SPI)CR1 register (LSBFIRST)Bit order HAL or direct register
UART (general)Rare direct controlByte/bit Software buffer handling

How Do You Handle Inflexible Hardware?

Some devices don’t allow configuration of bit order. In such cases, developers must rely on software-level bit reversal before sending or after receiving data. This applies often in I2C slave devicesfixed-format LCD modules, or legacy UART interfaces.

When sending uint16_t or uint32_t data to a device that expects a different byte or bit order, use helper functions to manually rearrange the bits or bytes. These can include bitwise operationslookup tables, or bit reversal macros.

Bit Reversal Function

				
					uint8_t reverseBits(uint8_t b) {
    b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
    b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
    b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
    return b;
}
				
			

Use this when a device expects MSB-first but your system outputs LSB-first.

Software-Level Adjustment Reference Table

ProblemSoftware SolutionUse Case Example
Bit order mismatchBit reversal functionSPI LCD with fixed MSB-first input
Byte order mismatchManual shifting or unionsEEPROM page write
Struct field mismatchMemory copy with reorderUART sensor payload

How Does Byte and Bit Order Impact Embedded and LCD Systems?

Byte and bit order directly affect how data is interpreted and displayed in embedded systems, especially when working with LCD modules. In systems using UARTSPI, or I2C interfaces, a mismatch in the expected MSB/LSB ordering can lead to misaligned charactersgarbled graphics, or broken commands. These issues arise when the display controller expects data in a different bit sequence or byte alignment than what the host microcontroller sends(What Are the Differences Between SPI and I2C for LCD Modules?).

Proper byte and bit manipulation ensures consistent and readable output across platformsprotocols, and architectures. In multi-endian environments, additional care is needed to preserve data meaning across different firmware builds and MCU types.

Byte and Bit Order in Embedded Interfaces

InterfaceBit Order UsedByte Order Considered LCD Implication
UARTLSB-firstYes Reversed text or incorrect chars
SPIMSB-firstYes Bit-shifted pixels, wrong colors
I2CMSB-firstYes Misinterpreted register data

How Does Bit Order Affect LCD Module Communication?

Many LCD modules using UART transmit and receive data LSB-first. If the microcontroller sends MSB-first, each byte will be misread, and the LCD might show inverted characters or ignore commands. In display systems using SPI, most modules expect MSB-first bit order, and failure to configure this correctly causes pixel data corruption.

To handle this, developers use either hardware configuration (like SPI.setBitOrder()) or bit reversal algorithms. Bitwise tools allow converting between LSB and MSB order.

Bit Alignment Fix for UART LCD

				
					uint8_t correctByte = reverseBits(originalByte); // Ensure correct UART bit sequence
				
			

Use this before transmitting a byte to the LCD if the protocol sends LSB-first but the device expects MSB-first.

Common LCD Communication Mismatch Scenarios

ScenarioError SeenCorrection Method
LSB data sent to MSB LCDCharacters display incorrectlyReverse bits before send
MSB SPI sent to LSB display driverInverted image or commands failUse SPI config or reverse
Struct data sent directlyPartial display data or glitchFlatten and align bytes

What Happens When Interfacing with Multi-Endian Systems?

When exchanging data across systems with different endianness, such as between a Little-Endian microcontroller and an MSB-first display controller, the same binary value may be interpreted differently. For example, 0x1234 sent from a Little-Endian MCU might arrive as 0x3412, resulting in incorrect rendering or command execution.

To avoid this, developers must detect the system’s endianness and convert multi-byte values accordingly before transmission or interpretation.

Cross-Platform Compatibility Technique

				
					uint16_t val = 0x1234;
uint8_t buffer[2];
// Convert to MSB-first for display
buffer[0] = (val >> 8) & 0xFF;
buffer[1] = val & 0xFF;
				
			

This guarantees that the LCD receives data in the expected order regardless of system architecture.

Portability Considerations Table

Platform PairEndian ConflictSolution
ARM MCU to LCD ControllerYesByte swap before transmission
PC software to embeddedOften YesSerialization layer
Mixed vendor SoC + LCDYesUse endian-neutral protocol

FAQ

What if the microcontroller and the device use different endianness?

You should reverse the byte order in software before sending the data to match the device’s expected format.

Can I use the same code for SPI and UART communication?

Not always. SPI and UART may use different bit orders, so you might need to adjust settings or reverse bits accordingly.

What happens if I write across a page boundary in EEPROM?

The device may wrap around and overwrite earlier data or skip the extra bytes, resulting in partial writes.

Do all LCD modules use MSB-first ordering?

No. Some use LSB-first, especially over UART. You must check the datasheet to know the exact requirement.

Is software bit reversal slow for real-time applications?

Yes, especially on slower microcontrollers. Use hardware settings or lookup tables if possible to improve speed.

Share:
Picture of Lyna

Lyna

Hi, I am Lyna, the author of this article. I have been in the LCD module industry for 13+ years and become to expert in small and medium-sized LCD modules.
I mainly provide wholesale services for LCD modules and professional business and technical support to factories and LCD dealers. I am happy to share my experience here with you, and you are welcome to discuss it with me.

Contact Us
Related Posts

Get A Quick Quote!

Hua Xian Jing Sales - Lyna Huang

GET FREE SAMPLE!

Over the years, rich experience in LCD module generation has led us to accumulate 10,000+ standard LCD modules in our standard library, download our catalog to select the LCD module that best suits your needs!