簡體   English   中英

Java讀/寫:我在這里做錯了什么?

[英]Java read/write: what am I doing wrong here?

這是我的代碼片段:

byte value = (byte) rand.nextInt();
TX.write(value);                    
int read = RX.read() & 0xFF;

我連接的硬件讓我回到了RX上我寫的東西。 只要我正在寫正數,那就行了。但是如果我寫一個負數我得到的東西與我寫的東西不符......

請問我錯過了什么?


編輯:示例輸出

Write: 66
Read: 66
OK AS EXPECTED

Write: -44
Read: 212
???

Write: -121
Read: 135

Write: -51
Read: 205
???

Write: -4
Read: 252
???

如果你寫一個負字節,然后你讀它並使用RX.read() & 0xFF將它分配到一個int,你將得到一個正數,因為int的符號位將為0。

嘗試

int read = RX.read();

BYTE為8位,其中1位保留用於符號,因此最大范圍是-128到127,所以當您使用負號的&0xFF時,您將獲得該范圍的無符號值。 因此,當你做-4時,它給出252如果你做-1然后它會給255等等。

同樣在你的代碼中你可以簡單地使用int cast,因為它在我的最后工作..例如: -

   byte b = -14;
    int i = (int)b;

看來,鑄造int ,以byte將代表intsigned int使用補(一個字節的范圍是[ 10000000 ] -128〜127 [ 01111111 ]注意, -111111111000000000 )。 但是, RX.read()將該byte視為unsigned int (范圍從0 [ 00000000 ]到255 [ 11111111 ])。

如果您只使用一個字節,則可以使用:

int r = RX.read() & 0xFF
int read = -(255 - r) if r > 128 else r 

這是因為默認情況下0xFF是一個32位的int。 以-51為例。 在二進制中,它使用2的補碼表示:

你這樣做:

                             11001101
& 00000000 00000000 00000000 FFFFFFFF

這使

00000000 00000000 00000000 11001101

= 205

你想要的是什么

  11001101
& FFFFFFFF

所以你應該這樣做

((byte) RX.read()) & ((byte) 0xFF)

見例子:

public static void main(String[] args) {
    int negative = -51;
    System.out.println((int) (negative & (byte) 0xFF)); // = -51
    System.out.println((int) (negative & 0xFF)); // = 205
}

暫無
暫無

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

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