[英]How do Little and Big Endian look if I want padding to 4 bytes?
不知何故,我有一個腦筋,無法找出適當的大和小端表示。 我有一個字節流,其中存儲了32位整數。
整數是1000十進制,即0x03E8十六進制。 在Little Endian中,當表示為兩個字節時,它將被存儲為E8 03
。
我假設如果我想要4字節填充,它將被存儲為00 00 E8 03
。 但是,當我使用BitConverter時,我得到了奇怪的結果:
// true
Console.WriteLine(BitConverter.IsLittleEndian);
var bytes = new byte[4] { 0x00, 0x00, 0xE8, 0x03 };
var convertedInt = BitConverter.ToInt32(bytes,0);
// 65536000 ?!
Console.WriteLine(convertedInt);
var inputInt = 1000;
var convertedBytes = BitConverter.GetBytes(inputInt);
// 4 Bytes: e8 03 00 00
Console.WriteLine("{0} Bytes: {1:x2} {2:x2} {3:x2} {4:x2}", convertedBytes.Length,
convertedBytes[0], convertedBytes[1],
convertedBytes[2], convertedBytes[3]);
這看起來像BitConverter壞了。 文件清楚地說:
GetBytes方法返回的數組中的字節順序取決於計算機體系結構是little-endian還是big-endian。
那么,我是否誤解了Little Endian是如何工作的,BitConverter是破碎的,還是我做錯了什么?
所以,我誤解了Little Endian是如何工作的
對。 Little endian意味着最不重要的部分首先出現 - 實際上是1000
Little endian: E8 03 00 00
Big endian: 00 00 03 E8
數量的最低顯著字節E8,所以它肯定要在一端去或其他-小尾數代表所說的那樣在開始; big-endian表示將它放在最后。 您建議的00 00 E8 03
表示位於中間位置。 根據Wikipedia Endianness頁面 ,這種表示確實存在,但很少 - 這稱為混合端或中端。
代碼確認:
using System;
class Test
{
static void Main()
{
var bytes = new byte[4] { 0xE8, 0x03, 0x00, 0x00 };
var convertedInt = BitConverter.ToInt32(bytes, 0);
Console.WriteLine(convertedInt); // 1000
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.