Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java读/写:我在这里做错了什么?_Java - Fatal编程技术网

Java读/写:我在这里做错了什么?

Java读/写:我在这里做错了什么?,java,Java,这是我的代码片段: byte value = (byte) rand.nextInt(); TX.write(value); int read = RX.read() & 0xFF; 我连接的硬件在RX上返回我在TX上写的内容。 只要我写的是正数就行了, 但是如果我写了一个负数,我得到的和我写的不匹配 请问我错过了什么 编辑:示例输出 Write: 66 Read: 66 OK AS EXPECTED Write: -44 Read: 212

这是我的代码片段:

byte value = (byte) rand.nextInt();
TX.write(value);                    
int read = RX.read() & 0xFF;
我连接的硬件在RX上返回我在TX上写的内容。 只要我写的是正数就行了, 但是如果我写了一个负数,我得到的和我写的不匹配

请问我错过了什么


编辑:示例输出

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

试一试


字节为8位,其中1位保留为符号最大值,因此其范围为-128到127,因此,当使用负号切换到&0xFF时,将获得该范围的无符号值。因此,当你做-4时,它给出252,如果你做-1,那么它将给出255,依此类推

在你的代码中,你也可以简单地使用int-casting,因为它在我这端工作。。 例如:-

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

似乎将
int
转换为
byte
将使用两个补码将
int
表示为
signed int
(对于一个字节,范围为[
10000000
]-128到127[
011111111
];注意
-1
11111111111
0
00000000
)。但是
RX.read()
字节
视为
无符号整数
(范围从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
}

不起作用…:-(((@LisaAnne)你能给出不起作用的示例输入和输出吗?例如,
rand.nextInt()
value
RX.read()
read
@LisaAnne Eran的值是正确的。尝试
字节读取=(字节)RX.read()如果你需要它作为一个int,只需在下一行中执行
int readAsInt=read;
。如果你愿意,你可以通过从大于127的数字中减去256来“修正”你的数字(212-256=-44,135-256=-121,…)
public static void main(String[] args) {
    int negative = -51;
    System.out.println((int) (negative & (byte) 0xFF)); // = -51
    System.out.println((int) (negative & 0xFF)); // = 205
}