|
import java.nio.ByteBuffer; public class mytest { public static void main(String[] args) { byte[] bytes = new byte[]{-76, -1, 32, 30, 36}; char[] chars = getChars(bytes); byte[] bytes2= getBytes(chars); char[] chars2 = getChars(bytes2); } } /**byte转char*/ Charset cs = Charset.forName (“UTF-8”); 如上代码,负数怎么还能转回来,现在来回转几次后,不对了。 |
|
![]() 10分 |
在Java中char和byte锁占用的字节数是不一样的,就比如byte的-1,和int的-1就差别很大,所以在转化的时候要进行&运算,比如转化-76的时候应该是-76&0xFF,
|
![]() 30分 |
大哥,您把正确的代码给注释掉了,
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
public class mytest {
public static void main(String[] args) {
// TODO Auto-generated method stub
byte[] bytes = new byte[]{-76, -1, 32, 30, 36};
char[] chars = getChars(bytes);
byte[] bytes2= getBytes(chars);
char[] chars2 = getChars(bytes2);
}
/** char转byte */
public static byte[] getBytes(char[] chars) {
int len = chars.length;
byte[] bytes = new byte[len];
for(int i=0;i<len;i++){
bytes[i]= (byte)(chars[i]);
}
return bytes;
}
/** byte转char */
public static char[] getChars(byte[] bytes) {
int len = bytes.length;
char[] chars = new char[len];
for(int i=0;i<len;i++){
chars[i]= (char)(bytes[i] & 0xff);
}
return chars;
}
}
|
![]() |
貌似可以了啊,还有其他办法嘛
|
![]() |
用没有注释的为什么不行
|
![char[]与byte[]互转负数问题 char[]与byte[]互转负数问题](https://www.codebye.com/wp-content/uploads/2015/01/jinpai.png)
![char[]与byte[]互转负数问题 char[]与byte[]互转负数问题](https://www.codebye.com/wp-content/uploads/2015/01/yinpai.png)