Java和无符号值 [英] Java and unsigned values

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

问题描述

我正在解析DatagramSocket中的无符号位。我总共有24位(或3个字节)进入 - 它们是:1个无符号8位整数,后跟16位有符号整数。但java从来没有将有符号的字节存储到字节/字节数组中?当java接收这些值时,你会丢失最后的第8位吗?

I'm parsing unsigned bits from a DatagramSocket. I have a total of 24bits (or 3 bytes) coming in - they are: 1 unsigned 8bit integer followed by a 16bit signed integer. But java never stores anything more than a signed byte into a byte/byte array? When java takes in these values, do you lose that last 8th bit?

DatagramSocket serverSocket = new DatagramSocket(666);
        byte[] receiveData = new byte[3]; <--Now at this moment I lost my 8th bit

        System.out.println("Binary Server Listing on Port: "+port);

        while (true)
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            byte[] bArray = receivePacket.getData();
            byte b = bArray[0];

        }

我现在丢失了第8位,因为我把它变成了一个字节?是不是我初始化了一个3字节的字节数组?

Did I now lose this 8th bit since I turned it into a byte? Was it wrong I initialized a byte array of 3 bytes?

推荐答案


当java接收这些值时你最后8位输掉了吗?

When java takes in these values, do you lose that last 8th bit?

没有。设置时你最终会得到负值。

No. You just end up with a negative value when it's set.

所以要获得0到255之间的值,最简单的方法是使用这样的东西:

So to get a value between 0 and 255, it's simplest to use something like this:

int b = bArray[0] & 0xff;

首先将字节提升为 int ,如果原始值中的高位为1,将对其进行符号扩展,导致25个前导1位。 & 0xff 然后再次摆脱前24位:)

First the byte is promoted to an int, which will sign extend it, leading to 25 leading 1 bits if the high bit is 1 in the original value. The & 0xff then gets rid of the first 24 bits again :)

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

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