在C中将大端转换为小端[不使用提供的函数] [英] convert big endian to little endian in C [without using provided func]

查看:18
本文介绍了在C中将大端转换为小端[不使用提供的函数]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 C 中编写一个将大端转换为小端的函数.我不能使用任何库函数.

I need to write a function to convert big endian to little endian in C. I can not use any library function.

推荐答案

假设你需要的是一个简单的字节交换,试试类似

Assuming what you need is a simple byte swap, try something like

无符号 16 位转换:

Unsigned 16 bit conversion:

swapped = (num>>8) | (num<<8);

无符号 32 位转换:

Unsigned 32-bit conversion:

swapped = ((num>>24)&0xff) | // move byte 3 to byte 0
                    ((num<<8)&0xff0000) | // move byte 1 to byte 2
                    ((num>>8)&0xff00) | // move byte 2 to byte 1
                    ((num<<24)&0xff000000); // byte 0 to byte 3

这会将字节顺序从位置 1234 交换到 4321.如果您的输入是 0xdeadbeef,则 32 位字节序交换可能会输出 0xefbeadde.

This swaps the byte orders from positions 1234 to 4321. If your input was 0xdeadbeef, a 32-bit endian swap might have output of 0xefbeadde.

上面的代码应该用宏或者至少是常量而不是幻数来清理,但希望它会有所帮助

The code above should be cleaned up with macros or at least constants instead of magic numbers, but hopefully it helps as is

正如另一个答案指出的那样,有平台、操作系统和指令集特定的替代方案可以比上述方案快得多.在 Linux 内核中有一些宏(例如 cpu_to_be32)可以很好地处理字节顺序.但是这些替代方案是特定于它们的环境的.在实践中,最好使用多种可用方法来处理字节序

as another answer pointed out, there are platform, OS, and instruction set specific alternatives which can be MUCH faster than the above. In the Linux kernel there are macros (cpu_to_be32 for example) which handle endianness pretty nicely. But these alternatives are specific to their environments. In practice endianness is best dealt with using a blend of available approaches

这篇关于在C中将大端转换为小端[不使用提供的函数]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆