双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

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

leoliangsir leoliangsir 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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[]转回来,能怎么样才能保持不变。
...全文
评论 4
收藏 已收藏
分享
返回顶部
leoliangsir
Java EE 67,535 成员 225,843 内容