Java charAt问题

调试的时候发现为什么不一致?

测试代码:

import org.junit.Test;

import static org.junit.Assert.*;

public class Test {

    @Test
    public void main() {
        new String(fromHexString("3900c29368")).charAt(2);
    }

    public static byte[] fromHexString(String hexString) {
        if (null == hexString || "".equals(hexString.trim())) {
            return new byte[0];
        }
        byte[] bytes = new byte[hexString.length() / 2];
        String hex;
        for (int i = 0; i < hexString.length() / 2; i++) {
            hex = hexString.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(hex, 16);
        }
        return bytes;
    }
}
阅读 1.6k
1 个回答

[57, 0, -109, 104] 你字符串结果是这个. charAt(2)是-109 , -109&0xFF = 147.

fromHexString("3900c29368")返回的是[57, 0, -62, -109, 104]。你用new String(byte[]) 最后应该走的java.lang.StringCoding#decodeUTF8_0方法,这个会遍历你传过来的字节数组,其中在遇到0xc2(注意-62就是0xc2)时,会和后一个字节一起处理,所有最后的字符串里只有四个字节了。

image.png

我也不清楚为啥要对0xc2,0xc3这样处理。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题