Java和无符号字节 [英] Java and unsigned Bytes

查看:120
本文介绍了Java和无符号字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用无符号字节数组。我需要通过网络将某些字符发送到服务器,其中一些字符大于127。

I need to make use of an array of unsigned bytes. I need to send certain characters over the network to a server and some of these characters are greater that 127.

我有一个简化的代码,可以尝试理解概念:

I have a simplified version of the code below to try and understand the concept:

int i= 160;
byte j = (byte) i;
System.out.println((byte)i);
System.out.println(j);

,结果为:
-96
-96

我需要打印160。如服务器所期望的那样字节160,如果接收到-96,则不接受该值。我使用int的原因是,当我阅读如何解决该问题时,我经常碰到使用int的建议,但是我不太理解,因为我需要数组为byte类型

I need to print 160. As the server is expecting a byte of 160 and if it receives -96 it does not accept the value. The reason I used an int is that when I was reading how to get around the problem, I often came across the suggestion to just use an int, but I don't quite understand that, as I need my array to be of type byte.

这是我发送数组的代码的一部分:

This is the part of my code where I send the array:

public boolean send(byte[] data) {
    try {
     out.write(data); // Write the data to the outStream
     out.flush();
    } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false; // Return false if the TCP Transmit failed 
// }
return false;
}

如果有人可以帮助我,我将非常感谢。

I would really appreciate it if some one could help me.

推荐答案

在Java中,有符号字节和无符号字节之间没有区别。以下两个都将为字节分配相同的值:

There is no distinction in Java between signed and unsigned bytes. Both of the following will assign the same value to a byte:

byte i = (byte)160;
byte j = (byte)-96;

由您作为开发人员来决定在打印时将它们视为带符号或无符号。默认设置是将它们打印为带符号,但是您可以通过将它们以无符号方式转换为整数来强制将它们打印为无符号。

Its up to you as a developer to treat them as signed or unsigned when you print them out. The default is to print them signed, but you can force them to print unsigned by converting them to an integer in an unsigned manner.

System.out.println(i); // -96
System.out.println(0xff&i); // 160

如果您想知道字节如何同时表示负数和正数,请阅读 Java中的二进制补码算法

If you want to know how bytes can represent both negative and positive numbers at the same time, read this article on two’s complement arithmetic in Java

这篇关于Java和无符号字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆