将Little Endian转换为Big Endian [英] Converting Little Endian to Big Endian
问题描述
全部,
我一直在网上练习编码问题。目前我正在处理一个问题陈述问题我们需要转换Big Endian< - >小端。但考虑到给出的示例,我无法记下步骤:
I have been practicing coding problems online. Currently I am working on a problem statement Problems where we need to convert Big Endian <-> little endian. But I am not able to jot down the steps considering the example given as:
123456789 converts to 365779719
我正在考虑的逻辑是:
1>获取整数值(因为我在Windows x86上) ,输入是Little endian)
2>生成相同的十六进制表示。
3>反转表示并生成大端整数值
The logic I am considering is :
1 > Get the integer value (Since I am on Windows x86, the input is Little endian)
2 > Generate the hex representation of the same.
3 > Reverse the representation and generate the big endian integer value
但我显然在这里遗漏了一些东西。
But I am obviously missing something here.
任何人都可以指导我。我在Java 1.5中编码
Can anyone please guide me. I am coding in Java 1.5
推荐答案
你需要意识到的是,endian交换处理代表整数的字节。所以4字节数字27看起来像 0x0000001B
。要转换该数字,需要转到 0x1B000000
...在您的示例中,123456789的十六进制表示为 0x075BCD15
需要转到 0x15CD5B07
或以十进制形式365779719。
The thing you need to realize is that endian swaps deal with the bytes that represent the integer. So the 4 byte number 27 looks like 0x0000001B
. To convert that number, it needs to go to 0x1B000000
... With your example, the hex representation of 123456789 is 0x075BCD15
which needs to go to 0x15CD5B07
or in decimal form 365779719.
Stacker发布的函数正在移动这些字节通过改变它们;更具体地说,语句 i& 0xff
从 i
获取最低字节,<< 24
然后将其向上移动24位,从位置1-8到25-32。所以通过表达式的每个部分。
The function Stacker posted is moving those bytes around by bit shifting them; more specifically, the statement i&0xff
takes the lowest byte from i
, the << 24
then moves it up 24 bits, so from positions 1-8 to 25-32. So on through each part of the expression.
例如代码,看看这个实用程序。
For example code, take a look at this utility.
这篇关于将Little Endian转换为Big Endian的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!