java string字节数组_java(基本类型或者String字符串)与(字节数组)相互转换
public class ByteConvert {
/**
* 整型轉化為字節數組
* @param id
* @return
*/
public byte[] int2Byte(int id){
byte[] arr=new byte[4];
for(int i=0;i<4;i++){
arr[i]=(byte)((id>>i*8)&0xff);
}
return arr;
}
/*
* 字節數組轉化為整型
*/
public int byte2Int(byte[] arr){
int count=0;
for(int i=0;i<4;i++){
int add=(int)((arr[i]&0xff)<
count+=add;
}
return count;
}
//long型轉化為byte[]
public byte[] long2Byte(long id){
byte[] arr=new byte[8];
for(int i=0;i
arr[i]=(byte)((id>>i*8)&0xff);
}
return arr;
}
//byte[]轉化為long
public long byte2long(byte[] arr){
long result=0;
for(int i=0;i
long add=(long)((arr[i]&0xff)<
result+=add;
}
return result;
}
public static void main(String[] args) {
ByteConvert bc=new ByteConvert();
//int轉化為byte[]
byte[] arr=bc.int2Byte(8143);
for(byte one:arr){
System.out.println(one);
}
//測試從字節數組轉化為整型
System.out.println(bc.byte2Int(arr));
//long轉化為byte[]
byte[] arr2=bc.long2Byte(8143);
for(byte one:arr2){
System.out.println(one);
}
//byte[]轉化為long
System.out.println(bc.byte2long(arr2));
//String轉化為byte[]
String str="我是lcc";
byte[] arr3=str.getBytes();
//byte[]轉化為String
String str2=new String(arr3);
System.out.println(str2);
}
運行結果:
-49
31
0
0
8143
-49
31
0
0
0
0
0
0
8143
我是lcc
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的java string字节数组_java(基本类型或者String字符串)与(字节数组)相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 多张表公用一个序列_Mysq
- 下一篇: java虚拟键盘_web虚拟键盘Virt