char[]与byte[]互转负数问题
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) {
Charset cs = Charset.forName ("UTF-8");
// Charset cs = Charset.forName ("US-ASCII");
CharBuffer cb = CharBuffer.allocate (chars.length);
cb.put (chars);
cb.flip ();
ByteBuffer bb = cs.encode (cb);
return bb.array();
}
/**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);
//// if(bytes[i]<0){
//// chars[i] = (char) (bytes[i]+256);
//// //chars[i]= (char)(bytes[i] & 0xff);
//// }else{
//// chars[i] = (char)bytes[i];
//// }
// }
// return chars;
Charset cs = Charset.forName ("UTF-8");
//Charset cs = Charset.forName ("US-ASCII");
ByteBuffer bb = ByteBuffer.allocate (bytes.length);
bb.put (bytes);
bb.flip ();
CharBuffer cb = cs.decode (bb);
return cb.array();
}
}
如上代码,负数怎么还能转回来,现在来回转几次后,不对了。
byte[]{-76, -1, 32, 30, 36}转为char[]后,再由char[]转回来,能怎么样才能保持不变。
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) {
Charset cs = Charset.forName ("UTF-8");
// Charset cs = Charset.forName ("US-ASCII");
CharBuffer cb = CharBuffer.allocate (chars.length);
cb.put (chars);
cb.flip ();
ByteBuffer bb = cs.encode (cb);
return bb.array();
}
/**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);
//// if(bytes[i]<0){
//// chars[i] = (char) (bytes[i]+256);
//// //chars[i]= (char)(bytes[i] & 0xff);
//// }else{
//// chars[i] = (char)bytes[i];
//// }
// }
// return chars;
Charset cs = Charset.forName ("UTF-8");
//Charset cs = Charset.forName ("US-ASCII");
ByteBuffer bb = ByteBuffer.allocate (bytes.length);
bb.put (bytes);
bb.flip ();
CharBuffer cb = cs.decode (bb);
return cb.array();
}
}
如上代码,负数怎么还能转回来,现在来回转几次后,不对了。
byte[]{-76, -1, 32, 30, 36}转为char[]后,再由char[]转回来,能怎么样才能保持不变。
...全文
相关推荐
Java 中 char 与 byte 的区别
重点讲述Java语言中容易混淆的char与byte的联系与区别
基于C语言char与unsigned char的区别介绍
本篇文章小编为大家介绍,基于C语言char与unsigned char的区别介绍。需要的朋友参考下
字符与16进制互转工具
1、代码使用vs2005开发的; 2、附件中提供了源码与使用说明书; 3、实现了字符与16进制码的互转功能,其中字符包含字母、阿拉伯数字、汉字;
C# 文本框输入负数验证
WinForm 中输入负数验证 C# 中textBox输入负数验证
计算器 C语言 带括号负数都能处理
强大的计算器功能实现,+-*/浮点数读取,带括号也能读取3*-5如此变态的形式也能读取,对负数处理很好的,文件读取,对空格也有识别



