转换大端在C小尾数[不使用提供FUNC] [英] convert big endian to little endian in C [without using provided func]

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

问题描述

我需要写一个函数来大端转换为小端在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.

在code以上,应清理与宏或者至少是常量,而不是神奇数字,但希望它有助于正如

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例如),它很好地处理字节顺序pretty。但这些替代特定于它们的环境。在实践中字节顺序最好是用现有方法的融合处理

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小尾数[不使用提供FUNC]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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