【问题标题】:Little endian to integer小端到整数
【发布时间】:2012-07-10 22:09:19
【问题描述】:

我得到这个字符串 8802000030000000C602000033000000000000800000008000000000000000001800000000000

这就是我期望从字符串转换的内容,

  88020000 long in little endian => 648 
  30000000 long in little endian => 48 
  C6020000 long in little endian => 710
 33000000 long in little endian => 51

左边是我从字符串中得到的值,右边是我期望的值。右侧的值可能是错误的,但是有什么办法可以从左侧获取右侧的值??

我在这里经历了几个线程,例如

How to convert an int to a little endian byte array?

C# Big-endian ulong from 4 bytes

我尝试了完全不同的功能,但没有什么能给我带来与我期望的差不多或接近的价值。

更新: 我正在阅读如下文本文件。大多数数据都是文本格式的,但突然间我得到一堆图形信息,我不知道如何处理它。

    RECORD=28 

cVisible=1
dwUser=0
nUID=23
c_status=1
c_data_validated=255
c_harmonic=0
c_dlg_verified=0
c_lock_sizing=0
l_last_dlg_updated=0
s_comment=
s_hlinks=
dwColor=33554432
memUsr0=
memUsr1=
memUsr2=
memUsr3=
swg_bUser=0
swg_dConnKVA=L0
swg_dDemdKVA=L0
swg_dCodeKVA=L0
swg_dDsgnKVA=L0
swg_dConnFLA=L0
swg_dDemdFLA=L0
swg_dCodeFLA=L0
swg_dDsgnFLA=L0
swg_dDiversity=L4607182418800017408
cStandard=0
guidDB={901CB951-AC37-49AD-8ED6-3753E3B86757}
l_user_selc_rating=0
r_user_selc_SCkA=
a_conn1=21
a_conn2=11
a_conn3=7
l_ct_ratio_1=x44960000
l_ct_ratio_2=x40a00000
l_set_ct_ratio_1=
l_set_ct_ratio_2=

c_ct_conn=0

   ENDREC
 GRAPHICS0=8802000030000000C602000033000000000000800000008000000000000000001800000000000
 EOF

【问题讨论】:

  • 为什么小端序中的 88020000 等于 648? 88020000 是十六进制的 53F1420,如果反转字节,则变为 20143F05,即十进制的 538197765。
  • @Robert: 88020000 已经是十六进制了,第三个数据包含非十进制数字就证明了这一点
  • @RobertHarvey 这有点令人困惑。对此感到抱歉。

标签: c# int endianness


【解决方案1】:

根据您要如何解析输入字符串,您可以执行以下操作:

string input = "8802000030000000C6020000330000000000008000000080000000000000000018000000";

for (int i = 0; i < input.Length ; i += 8)
{
    string subInput = input.Substring(i, 8);
    byte[] bytes = new byte[4];
    for (int j = 0; j < 4; ++j)
    {
        string toParse = subInput.Substring(j * 2, 2);
        bytes[j] = byte.Parse(toParse, NumberStyles.HexNumber);
    }

    uint num = BitConverter.ToUInt32(bytes, 0);
    Console.WriteLine(subInput + " --> " + num);
}

88020000 --> 648
30000000 --> 48
C6020000 --> 710
33000000 --> 51
00000080 --> 2147483648
00000080 --> 2147483648
00000000 --> 0
00000000 --> 0
18000000 --> 24

【讨论】:

  • 你的代码很棒。这是非常快速的答案。我只是改变了一件事,而不是“uint num = BitConverter.ToUInt32(bytes, 0);”我使用“int num = BitConverter.ToInt32(bytesi, 0);”
【解决方案2】:

你真的是说那是一个字符串吗?它看起来是这样的:你有一堆 32 位的字,每个字用 8 个十六进制数字表示。每一个都以小端顺序呈现,低字节在前。您需要将其中的每一个解释为整数。因此,例如,88020000 是 88 02 00 00,即 0x00000288。

如果您能明确说明您所拥有的是什么——一个字符串、某种数字类型的数组,或者什么——那么进一步向您提供建议会更容易。

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 2012-06-16
    • 2015-04-14
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2016-06-13
    相关资源
    最近更新 更多