簡體   English   中英

如何在java中連接兩個字節?

[英]How can I concatenate two bytes in java?

我有一個名為writePos的整數,其值介於[0,1023]之間。 我需要將它存儲在名為bucket的字節數組的最后兩個字節中。 所以,我想我需要將它表示為數組最后兩個字節的串聯。

  1. 我如何將writePos分解為兩個字節,當連接並轉換為int ,再次生成writePos

  2. 一旦我將其分解為字節,我將如何進行連接?

這將由ByteBuffer覆蓋高級別。

short loc = (short) writeLocation;

byte[] bucket = ...
int idex = bucket.length - 2;
ByteBuffer buf = ByteBuffer.wrap(bucket);
buf.order(ByteOrder.LITTLE__ENDIAN); // Optional
buf.putShort(index, loc);

writeLocation = buf.getShort(index);

可以指定訂單,也可以保留默認值(BIG_ENDIAN)。

  1. ByteBuffer包裝原始字節數組,並且也改變了對字節數組的ByteBuffer效果。
  2. 可以使用順序寫入和讀取定位(搜索),但在這里我使用重載方法立即使用index進行定位。
  3. putShort寫入字節數組,修改兩個字節,一個短。
  4. getShort從字節數組中讀取一個short,它可以放在int中。

說明

java中的short是一個雙字節(帶符號)整數。 這就是意思。 順序是LITTLE_ENDIAN:最低有效字節優先(n%256,n / 256)還是大端。

按位運算。

字節:

byte[] bytes = new byte[2];
// This uses a bitwise and (&) to take only the last 8 bits of i
byte[0] = (byte)(i & 0xff); 
// This uses a bitwise and (&) to take the 9th to 16th bits of i
// It then uses a right shift (>>)  then move them right 8 bits
byte[1] = (byte)((i & 0xff00) >> 8);from byte:

回到另一個方向

// This just reverses the shift, no need for masking.
// The & here is used to handle complications coming from the sign bit that
// will otherwise be moved as the bytes are combined together and converted
// into an int
i = (byte[0] & 0xFF)+(byte[1] & 0xFF)<<8;

這里有一些工作示例,您可以使用以下內容進行轉換: http//ideone.com/eRzsun

您需要將整數拆分為兩個字節。 高字節和低字節。 根據您的描述,它將作為bug endian存儲在數組中。

int writeLocation = 511;
byte[] bucket = new byte[10];
// range checks must be done before
// bitwise right rotation by 8 bits
bucket[8] = (byte) (writeLocation >> 8); // the high byte
bucket[9] = (byte) (writeLocation & 0xFF); // the low byte

System.out.println("bytes = " + Arrays.toString(bucket));

// convert back the integer value 511 from the two bytes
bucket[8] = 1;
bucket[9] = (byte) (0xFF);
// the high byte will bit bitwise left rotated
// the low byte will be converted into an int
// and only the last 8 bits will be added
writeLocation = (bucket[8] << 8) + (((int) bucket[9]) &  0xFF);
System.out.println("writeLocation = " + writeLocation);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM