char[]与byte[]互转负数问题

leoliangsir 2014-09-25 05:59:42
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[]转回来,能怎么样才能保持不变。
...全文
386 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
leoliangsir 2014-09-26
  • 打赏
  • 举报
回复
用没有注释的为什么不行
leoliangsir 2014-09-26
  • 打赏
  • 举报
回复
貌似可以了啊,还有其他办法嘛
tianmaxingkong139 2014-09-25
  • 打赏
  • 举报
回复
大哥,您把正确的代码给注释掉了,

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;

	}
}
tianmaxingkong139 2014-09-25
  • 打赏
  • 举报
回复
在Java中char和byte锁占用的字节数是不一样的,就比如byte的-1,和int的-1就差别很大,所以在转化的时候要进行&运算,比如转化-76的时候应该是-76&0xFF,

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧