2016-05-19 36 views
2

我正在構建一個使用Android Studio的應用程序,並且在我的項目中,我需要對字節數組進行很多類似short/int的轉換。我也希望我的應用程序接收來自以C語言編碼的機器人的數據,並且機器人發送了一個結構,其中包含許多uint16-32,int16-32 .... 我發現很多帖子和代碼幫助了我在bytearray中轉換了我的屬性,但我總是看到有人在討論Little和Big Endian,我無法理解它們之間的區別。如果有人可以向我解釋.... 注意:機器人通過TCP協議通過Wifi套接字發送數據Java中的小端和大端(Android)

+0

讀https://en.wikipedia.org/wiki/Endianness或http://stackoverflow.com/questions/22030657/little-endian-vs-大端和相關問題。 'int'需要4個字節,字節順序是關於它們是否被排序爲0,1,2,3或3,2,1,0(例如,在像套接字之類的字節流中) – zapl

回答

2

小端和大端簡單地指其中的數據結構的字節出現的順序。

想象一下,您有一個由十六進制值0xabcd表示的16位整數。由於8位= 1字節,所以我們的整數由兩個字節ab和cd組成。在Big Endian系統中,最重要的字節放置在較低的內存地址中,而在Little Endian系統中,我們將它們放在較高的一箇中。

爲了直觀地展現這一點,假設我們已經把我們的整數在內存地址0

在Big Endian的系統,我們的記憶是這樣的:

Memory address -> | 0 | 1 | 
Value   -> | ab | cd | 

在小端系統,它看起來像這樣:

Memory address -> | 0 | 1 | 
Value   -> | cd | ab | 

傳統上,網絡字節順序是Big Endian。

+1

和Android(本地)是Little-尾段。 – DragonLord

1

將整數轉換爲字節流時,通常將整數分成字節併發送字節逐個。如果發送的第一個字節包含最低有效位,則它是小端。如果發送的第一個字節包含最高有效位,則它是大端。在小端中,1將由字節1表示,接着是包含0的字節。(因爲字節可以用兩個十六進制數字表示,所以它們通常用這種方式表示)。因此短整數1被轉換爲字節01 00並且短整數256變成小尾數中的字節00 01。在大端,1字節流是00 01和256變爲01 00

參見https://en.wikipedia.org/wiki/Endianness

0
String path=」root/subdir/filename.extension」; 

File f=new File(path); 

RandomAccessFile raf=new RandomAccessFile(f,」r」); 

ByteBuffer bb; 

    char c; 

int i; 



    ch=raf.readChar(); 

     bb=ByteBuffer.allocate(4); //4 byte buffer 

bb.order(ByteOrder.BIG_ENDIAN); 

bb.putChar(ch); //store 2 byte unsigned value in byte buffer and reach 2  
position forward //in buffer 

bb.order(ByteOrder.LITTLE_ENDIAN); 

bb.position(0); //goto start of buffer again for reading 

ch=bb.getChar(); //retrieve 2 byte unsigned value from byte buffer 

i=(int) ch; //always store a 2-byte unsigned value (e.g.unsigned char) into  
a 4-byte signed //datatype to avoid storing as 2’s compliment negative no. 

    //now 4 byte integer ‘i’ contains a 2-byte unsigned +ve integer value for  
    processing 

    System.out.println(「2 byte unsigned int value=」,i); 

全碼在這裏看到:program to read and store big and little endian