乐闻世界logo
搜索文章和话题

How to convert big endian to little endian in C without using library functions?

1个答案

1

In C programming, Big-Endian and Little-Endian are two byte orders that define how multi-byte data types (such as integers and floating-point numbers) are stored in memory. Big-Endian refers to the most significant byte being stored at the lowest memory address, while Little-Endian refers to the least significant byte being stored at the lowest memory address.

To convert Big-Endian to Little-Endian without using library functions, bit manipulation or unions can be used for manual conversion. Here are two methods:

Method One: Bit Manipulation

For a 32-bit integer, we can swap byte positions using bit shifting and masking operations to convert from Big-Endian to Little-Endian. The following is an example function for converting a 32-bit integer:

c
#include <stdio.h> unsigned int swapEndian(unsigned int num) { return ((num >> 24) & 0xff) | // Shift the highest byte to the lowest position ((num << 8) & 0xff0000) | // Shift the second highest byte to the second lowest position ((num >> 8) & 0xff00) | // Shift the second lowest byte to the second highest position ((num << 24) & 0xff000000); // Shift the lowest byte to the highest position } int main() { unsigned int num = 0x12345678; printf("Original: 0x%x\n", num); unsigned int swapped = swapEndian(num); printf("Swapped: 0x%x\n", swapped); return 0; }

In this function, bit shifting and bitwise AND operations are used to rearrange the byte order.

Method Two: Unions and Structs

Using unions is another method for byte swapping. Unions allow different data types to be stored in the same memory location, enabling us to input data as one type and read it as another type to convert byte order.

c
#include <stdio.h> typedef union { unsigned int num; unsigned char bytes[4]; } EndianConverter; unsigned int swapEndian(EndianConverter converter) { EndianConverter result; result.bytes[0] = converter.bytes[3]; result.bytes[1] = converter.bytes[2]; result.bytes[2] = converter.bytes[1]; result.bytes[3] = converter.bytes[0]; return result.num; } int main() { EndianConverter converter; converter.num = 0x12345678; printf("Original: 0x%x\n", converter.num); unsigned int swapped = swapEndian(converter); printf("Swapped: 0x%x\n", swapped); return 0; }

In this example, we rearrange the byte order within the union by swapping the byte array elements, then output the result as an integer.

Both methods can effectively convert Big-Endian to Little-Endian in C without relying on external library functions.

2024年6月29日 12:07 回复

你的答案