You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将有符号byte[]转为对应无符号值的char/short数组?

将有符号byte[]转为无符号char[]/short[]的可行方案

核心逻辑说明

Java的byte是有符号类型,要转为无符号值,本质是通过& 0xFF清除高位符号位,得到0-255区间的数值,再存入char[]或short[]。以下是几种实现方式:

1. 手动循环(最直接无依赖)

性能稳定,代码直观:

byte[] signedBytes = Hex.decodeHex(hexStr);
// 转为char[]
char[] unsignedChars = new char[signedBytes.length];
for (int i = 0; i < signedBytes.length; i++) {
    unsignedChars[i] = (char) (signedBytes[i] & 0xFF);
}
// 转为short[]
short[] unsignedShorts = new short[signedBytes.length];
for (int i = 0; i < signedBytes.length; i++) {
    unsignedShorts[i] = (short) (signedBytes[i] & 0xFF);
}

2. Stream管道实现(Java 8+)

用Stream简化代码,可读性较好:

byte[] signedBytes = Hex.decodeHex(hexStr);
// 转为char[]
char[] unsignedChars = IntStream.range(0, signedBytes.length)
        .map(i -> signedBytes[i] & 0xFF)
        .mapToObj(c -> (char) c)
        .toArray(Character[]::new);
// 转为short[]
short[] unsignedShorts = IntStream.range(0, signedBytes.length)
        .map(i -> signedBytes[i] & 0xFF)
        .mapToShort(s -> (short) s)
        .toArray();

3. 第三方库辅助(Apache Commons/Ga v a)

  • Apache Commons Lang:借助ArrayUtils封装转换逻辑:
byte[] signedBytes = Hex.decodeHex(hexStr);
short[] unsignedShorts = ArrayUtils.toObject(signedBytes)
        .stream()
        .mapToShort(b -> (short) (b & 0xFF))
        .toArray();
  • Guava:用Bytes类配合Byte.toUnsignedInt方法:
byte[] signedBytes = Hex.decodeHex(hexStr);
short[] unsignedShorts = Bytes.asList(signedBytes)
        .stream()
        .mapToShort(b -> (short) Byte.toUnsignedInt(b))
        .toArray();

关于你提到的工具类的补充说明

  • java.nio.ByteBuffer:确实无法直接完成无符号转换,其get()方法返回的仍是有符号byte,需手动处理符号位。
  • java.nio.charset.CharsetDecoder:不存在所谓的“恒等解码器”,解码器的作用是基于字符集将字节解码为字符,并非单纯的无符号数值转换,不符合需求。

内容的提问来源于stack exchange,提问作者davidbak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:21:01