小编Kul*_*ngh的帖子

为什么我们不能将整数文字作为参数传递给以字节为形式参数的方法

查询1:

byte a = 0; // int to byte implicit conversion happens, correct!, no CTE [compile time error]
setByte(0); // CTE!, why ? implicit conversion do not happen here 
void setByte(byte b){}
Run Code Online (Sandbox Code Playgroud)

查询2:

byte b_byte = 128 - 1; // integer literal computation results to 127 int which implicitly casts to byte and as 127 is in range of byte so no CTE, Correct!
int a_int = 2147483647; // in range of int, so no CTE
int b_int = 2147483648 …
Run Code Online (Sandbox Code Playgroud)

java

2
推荐指数
1
解决办法
55
查看次数

字符串字节编码问题

鉴于我有以下功能

static void fun(String str) {
        System.out.println(String.format("%s | length in String: %d | length in bytes: %d | bytes: %s", str, str.length(), str.getBytes().length, Arrays.toString(str.getBytes())));
    }
Run Code Online (Sandbox Code Playgroud)

调用fun("ó");它的输出是

ó | length in String: 1 | length in bytes: 2 | bytes: [-61, -77]
Run Code Online (Sandbox Code Playgroud)

所以这意味着字符 ó 需要 2 个字节来表示,并且根据 Character 类文档,Java 中的默认值也是 UTF-16,考虑到当我执行以下操作时

System.out.println(new String("ó".getBytes(), StandardCharsets.UTF_16));// output=?
System.out.println(new String("ó".getBytes(), StandardCharsets.ISO_8859_1));// output=ó
System.out.println(new String("ó".getBytes(), StandardCharsets.US_ASCII));// output=??
System.out.println(new String("ó".getBytes(), StandardCharsets.UTF_8));// output=ó
System.out.println(new String("ó".getBytes(), StandardCharsets.UTF_16BE));// output=?
System.out.println(new String("ó".getBytes(), StandardCharsets.UTF_16LE));// output=?
Run Code Online (Sandbox Code Playgroud)

为什么任何 UTF_16、UTF_16BE、UTF_16LE 字符集都无法正确解码字节,因为字节代表 16 …

java string character-encoding

0
推荐指数
1
解决办法
34
查看次数

标签 统计

java ×2

character-encoding ×1

string ×1