3

我想将JavaString str转换为byte[] b具有以下特征:

  • b是一个有效的 C 字符串(它有b.length = str.length() + 1b[str.length()] == 0.
  • 中的字符b是通过将字符转换str为 8 位 ASCII 字符获得的。

最有效的方法是什么——最好是现有的库函数?可悲的是,str.getBytes("ISO-8859-1")不符合我的第一个要求...

4

2 回答 2

11
// do this once to setup
CharsetEncoder enc = Charset.forName("ISO-8859-1").newEncoder();

// for each string
int len = str.length();
byte b[] = new byte[len + 1];
ByteBuffer bbuf = ByteBuffer.wrap(b);
enc.encode(CharBuffer.wrap(str), bbuf, true);
// you might want to ensure that bbuf.position() == len
b[len] = 0;

这需要分配几个包装对象,但不会复制字符串字符两次。

于 2013-07-19T04:09:17.013 回答
7

你可以str.getBytes("ISO-8859-1")在最后使用一个小技巧:

byte[] stringBytes=str.getBytes("ISO-8859-1");
byte[] ntBytes=new byte[stringBytes.length+1];
System.arraycopy(stringBytes, 0, ntBytes, 0, stringBytes.length);

arraycopy 相对较快,因为它可以在许多情况下使用本机技巧和优化。新数组在我们没有覆盖它的所有地方都填充了空字节(基本上只是最后一个字节)。

ntBytes是你需要的数组。

于 2013-07-19T02:34:26.083 回答