Java中的Big/Little問題

來源:互聯網
上載者:User
問題 Java中的Big/Little問題
1. 解決Endian問題:一個總結
Java二進位檔案中的所有東西都以big-endian形式存在,高位元組優先,這有時被稱為網路順序。這是一個好的訊息,意味著如果你只使用Java。所有檔案在所有平台(Mac,PC,Solaris等)上按同樣的方式進行處理。可以自由地交換位元據,以電子形式在Internet上,或在磁碟片上,而無需考慮endian問題。存在的問題是當你與那些不是使用Java編寫的程式交換資料檔案時,會存在一些問題。因為這些程式使用的是little-endian順序,通常是在PC上使用的C語言。有些平台內部使用big-endian位元組順序(Mac,IBM390);有些平台使用little-endian位元組順序(Intel)。Java對使用者隱瞞了endian問題。

在二進位檔案中,在域之間沒有分割符,檔案是二進位形式的,不可讀的ASCII。如果你想讀的資料不是標準格式,通常由非Java程式準備的。可以由四種選擇:

1). 重寫提供輸入檔案的輸出程式。它可以直接輸出big-endian位元組流DataOutputStream或者字元DataOutputSream格式。

2). 寫一個獨立的翻譯程式,讀和排列位元組。可以用任何語言編寫。

3). 以位元組形式讀資料,並重新安排它們(on the fly)。

4). 最簡單的方式是,使用我編寫的LEDataInputStream, LEDataOutputStream 和LERandomAccessFile類比 DataInputStream, DataOutputStream and RandomAccessFile ,它們使用的是little-endian位元組流。 You can read about LEDataStream. You can download the code and source free. You can get help from the File I/O Amanuensis to show you how to use the classes. Just tell it you have little-endian binary data.

2.你可能甚至不會有任何問題。
從C來的許多Java新手可能會認為需要考慮它們所依賴的平台內部所使用的是big還是little問題。在Java中這不是一個問題。進一步,不藉助於本地類,你無法知道它們是如何儲存的。Java has no struct I/O and no unions or any of the other endian-sensitive language constructs.

僅在與遺留的C/C++應用程式通訊時需要考慮endian問題。下列代碼在big or little endian機器上都將產生同樣的結果:

// take 16-bit short apart into two 8-bit bytes.
short x = 0xabcd;
byte high = (byte) (x >>> 8);
byte low = (byte) x;/* cast implies & 0xff */
System.out.println ("x=" + x + " high=" + high + " low=" + low );

3.讀Little-Endian Binary Files
The most common problem is dealing with files stored in little-endian format.

I had to implement routines parallel to those in java.io.DataInputStream which reads raw binary, in my LEDataInputStream and LEDataOutputStream classes. Don't confuse this with the io.DataInput human-readable character-based file-interchange format.

If you wanted to do it yourself, without the overhead of the full LEDataInputStream and LEDataOutputStream classes, here is the basic technique:

Presuming your integers are in 2's complement little-endian format, shorts are pretty easy to handle:


--------------------------------------------------------------------------------

short readShortLittleEndian( )

{
// 2 bytes
int low = readByte() & 0xff;
int high = readByte() & 0xff;
return (short )(high << 8 | low);
}

Or if you want to get clever and puzzle your readers, you can avoid one mask since the high bits will later be shaved off by conversion back to short.

short readShortLittleEndian( )

{
// 2 bytes
int low = readByte() & 0xff;
int high = readByte();
// avoid masking here
return (short )(high << 8 | low);
}


--------------------------------------------------------------------------------

Longs are a little more complicated:


--------------------------------------------------------------------------------

long readLongLittleEndian( )

{
// 8 bytes
long accum = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy+ =8 )

{
// must cast to long or shift done modulo 32
accum |= ( long)(readByte () & 0xff) << shiftBy;
}

return accum;
}


--------------------------------------------------------------------------------

In a similar way we handle char and int.


--------------------------------------------------------------------------------

char readCharLittleEndian( )

{
// 2 bytes
int low = readByte() & 0xff;
int high = readByte();
return (char )(high << 8 | low);
}


--------------------------------------------------------------------------------

int readIntLittleEndian( )

{
// 4 bytes
int accum = 0;
for ( int shiftBy = 0; shiftBy < 32; shiftBy+ =8 )

{
accum |= (readByte () & 0xff) << shiftBy;
}

return accum;
}


--------------------------------------------------------------------------------

Floating point is a little trickier. Presuming your data is in IEEE little-endian format, you need something like this:


--------------------------------------------------------------------------------

double readDoubleLittleEndian( )

{
long accum = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy+ =8 )

{
// must cast to long or shift done modulo 32
accum |= ( (long)(readByte() & 0xff)) << shiftBy;
}

return Double.longBitsToDouble (accum);
}


--------------------------------------------------------------------------------

float readFloatLittleEndian( )

{
int accum = 0;
for ( int shiftBy = 0; shiftBy < 32; shiftBy+ =8 )

{
accum |= (readByte () & 0xff) << shiftBy;
}

return Float.intBitsToFloat (accum);
}


--------------------------------------------------------------------------------

You don't need a readByteLittleEndian since the code would be identical to readByte, though you might create one just for consistency:


--------------------------------------------------------------------------------

byte readByteLittleEndian( )

{
// 1 byte
return readByte();
}


--------------------------------------------------------------------------------

4.History
In Gulliver's travels the Lilliputians liked to break their eggs on the small end and the Blefuscudians on the big end. They fought wars over this. There is a computer analogy. Should numbers be stored most or least significant byte first? This is sometimes referred to as byte sex.

Those in the big-endian camp (most significant byte stored first) include the Java VM virtual computer, the Java binary file format, the IBM 360 and follow-on mainframes such as the 390, and the Motorola 68K and most mainframes. The Power PC is endian-agnostic.

Blefuscudians (big-endians) assert this is the way God intended integers to be stored, most important part first. At an assembler level fields of mixed positive integers and text can be sorted as if it were one big text field key. Real programmers read hex dumps, and big-endian is a lot easier to comprehend.

In the little-endian camp (least significant byte first) are the Intel 8080, 8086, 80286, Pentium and follow ons and the AMD 6502 popularised by the Apple ][.

Lilliputians (little-endians) assert that putting the low order part first is more natural because when you do arithmetic manually, you start at the least significant part and work toward the most significant part. This ordering makes writing multi-precision arithmetic easier since you work up not down. It made implementing 8-bit microprocessors easier. At the assembler level (not in Java) it also lets you cheat and pass addresses of a 32-bit positive ints to a routine expecting only a 16-bit parameter and still have it work. Real programmers read hex dumps, and little-endian is more of a stimulating challenge.

If a machine is word addressable, with no finer addressing supported, the concept of endianness means nothing since words are fetched from RAM in parallel, both ends first.

5.What Sex Is Your CPU?
Byte Sex Endianness of CPUs

CPU
Endianness Notes

AMD 6502, Duron, Athlon, Thunderird
little
6502 was used in the Apple ][, the Duron, Athlon and Thunderbird in Windows 95/08/ME/NT/2000/XP

Apple ][ 6502
little


Apple Mac 68000
big
Uses Motorola 68000

Apple Power PC
big
CPU is bisexual but stays big in the Mac OS.

Burroughs 1700, 1800, 1900
?
bit addressable. Used different interpreter firmware instruction sets for each language.

Burroughs 7800
?
Algol machine

CDC LGP-30
word-addressable only, hence no endianness
31½ bit words. Low order bit must be 0 on the drum, but can be 1 in the accumulator.

CDC 3300, 6600
word-addressable
?

DEC PDP, Vax
little


IBM 360, 370, 380, 390
big


IBM 7044, 7090
word addressable
36 bits

IBM AS-400
big
?

Power PC
either
The endian-agnostic Power-PC's have a foot in both camps. They are bisexual, but the OS usually imposes one convention or the other. e.g. Mac PowerPCs are big-endian.

Intel 8080, 8080, 8086, 80286, 80386, 80486, Pentium I, II, III, IV
little
Chips used in PCs

Intel 8051
big


MIPS R4000, R5000, R10000
big
Used in Silcon Graphics IRIX.

Motorola 6800, 6809, 680x0, 68HC11
big
Early Macs used the 68000. Amiga.

NCR 8500
big


NCR Century
big


Sun Sparc and UltraSparc
big
Sun's Solaris. Normally used as big-endian, but also has support for operating for little-endian mode, including being able to switch endianness under program control for particular loads and stores.

Univac 1100
word-addressable
36-bit words.

Univac 90/30
big
IBM 370 clone

Zilog Z80
little
Used in CPM machines.


If you know the endianness of other CPUs/OSes/platforms please email me at roedy@mindprod.com.

In theory data can have two different byte sexes but CPUs can have four. Let us give thanks, in this world of mixed left and right hand drive, that there are not real CPUs with all four sexes to contend with.

The Four Possible Byte Sexes for CPUS

Which Byte
Is Stored in the
Lower-Numbered
Address?
Which Byte
Is Addressed?
Used In
LSB
LSB
Intel, AMD, Power PC, DEC.

LSB
MSB
none that I know of.

MSB
LSB
Perhaps one of the old word mark architecture machines.

MSB
MSB
Mac, IBM 390, Power PC



--------------------------------------------------------------------------------

You are visitor number 8680.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.