我们可以在 Java 中创建无符号字节吗 [英] Can we make unsigned byte in Java

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

问题描述

我正在尝试将有符号字节转换为无符号字节.问题是我收到的数据是无符号的,Java 不支持无符号字节,所以当它读取数据时,它把它当作有符号的.

I am trying to convert a signed byte in unsigned. The problem is the data I am receiving is unsigned and Java does not support unsigned byte, so when it reads the data it treats it as signed.

我尝试通过以下从 StackOverflow 获得的解决方案来转换它.

I tried it to convert it by the following solution I got from Stack Overflow.

public static int unsignedToBytes(byte a)
{
    int b = a & 0xFF;
    return b;
}

但是当它再次转换为字节时,我得到相同的签名数据.我试图将此数据用作只接受一个字节作为参数的 Java 函数的参数,因此我不能使用任何其他数据类型.我该如何解决这个问题?

But when again it's converted in byte, I get the same signed data. I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter, so I can't use any other data type. How can I fix this problem?

推荐答案

我不确定我是否理解你的问题.

I'm not sure I understand your question.

我刚刚尝试过这个,对于字节 -12(有符号值),它返回整数 244(相当于无符号字节值,但输入为 int):

I just tried this and for byte -12 (signed value) it returned integer 244 (equivalent to unsigned byte value but typed as an int):

  public static int unsignedToBytes(byte b) {
    return b & 0xFF;
  }

  public static void main(String[] args) {
    System.out.println(unsignedToBytes((byte) -12));
  }

这是你想做的吗?

Java 不允许将 244 表示为 byte 值,就像 C 一样.要表示 Byte.MAX_VALUE (127) 以上的正整数,您必须使用不同的整数类型,如 shortintlong.

Java does not allow to express 244 as a byte value, as would C. To express positive integers above Byte.MAX_VALUE (127) you have to use a different integral type, like short, int or long.

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

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