我正在尝试将单个字节转换为字符串,然后再返回原始字节。然而,下面的断言失败了。任何建议将不胜感激
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.assertEquals;
public class ByteTest {
private static final String CHARSET = "UTF-8";
@Test
public void test() throws UnsupportedEncodingException {
byte b = (byte)(220);
String s = new String(new byte[]{b}, CHARSET);
byte[] parsed = s.getBytes(CHARSET);
assertEquals(b, parsed[0]); //fails
}
}
最佳答案
字节 220 (0xDC) 本身是无效的 UTF-8。 UTF-8以字节 0xA1..0xF5 开头的字符需要第二个字节。
尝试另一种编码,例如ISO-8859-1,它在 Java 中有效地进行了 1 对 1 字节到字符的往返。
public class ByteTest {
private static final String CHARSET = "ISO-8859-1";
@Test
public void test() throws UnsupportedEncodingException {
byte b = (byte) (220);
String s = new String(new byte[] { b }, CHARSET);
byte[] parsed = s.getBytes(CHARSET);
assertEquals(b, parsed[0]);
}
}
关于java - 将单个字节转换为字符串并返回字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348921/