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

查看:242
本文介绍了我们可以在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.

我试过它转换我通过以下解决方案从Stack  Overflow获得。

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表示为字节值,就像C表示的那样。在以上表示正整数> Byte.MAX_VALUE (127)您必须使用其他整数类型,例如 short int long

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 an other integer type, like short, int or long.

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

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