将有符号字节数组转换为无符号字节 [英] converting an array of signed bytes to unsigned bytes

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

问题描述

我有一个字节数组.

bytes[] = [43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0]

我想将其转换为Java中的无符号字节.这就是我所做的:创建一个新数组,并使用&复制值.0xFF:

I want to convert it to unsigned bytes in Java. this is what I did: created a new array and copy the values with & 0xFF:

    this.bytes = new byte[bytes.length];
    for (int i=0;i<bytes.length;i++)
        this.bytes[i] = (byte) (bytes[i] & 0xFF);

,但是值在新数组中也保持负数.我在做什么错了?

but the values stay negative in the new array as well. what am I doing wrong?

推荐答案

bytes 在Java中总是经过签名的.

bytes in Java are always signed.

如果要获取这些字节的无符号值,可以将它们存储在 int 数组中:

If you want to obtained the unsigned value of these bytes, you can store them in an int array:

byte[] signed = {43, 0, 0, -13, 114, -75, -2, 2, 20, 0, 0};
int[] unsigned = new int[signed.length];
for (int i = 0; i < signed.length; i++) {
    unsigned[i] = signed[i] & 0xFF;
}

您将获得以下值:

[43, 0, 0, 243, 114, 181, 254, 2, 20, 0, 0]

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

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