java byte(字节_【原创】Java中Byte字节流处理的自定义方法库2
1.把整型轉換成指定長度的數組字節流
public static byte[] int2bytes(int integer, int len) {
//?? if (integer < 0) { throw new IllegalArgumentException("Can not cast negative to bytes : " + integer); }
ByteArrayOutputStream bo = new ByteArrayOutputStream();
for (int i = 0; i < len; i++) {
bo.write(integer);
integer = integer >> 8;
}
byte[] res=reversEndian(bo.toByteArray(),len);
return res;
}
private static byte[] reversEndian(byte str[],int len) {
byte b;
byte res[]=new byte[len];
for(int i=0;i
{
b=str[i];
res[len-i-1]=b;
}
return res;
}
2.把整型轉換成TLV方式的字節數組流
public static byte[] int2TLVbytes(int tag,int value,int len) throws IOException{
byte[] tag1=int2bytes(tag,4);
byte[] length1=int2bytes(len,4);
byte[] value1=int2bytes(value,len);
byte[] buff=pack(tag1,length1,value1);
return buff;
}
3.把UTF-8的string轉換成指定長度的字節數組流,不足部分補0x00
public static byte[] UTF8string2bytes(String source, int length,byte fillByte) {
byte[] dst = new byte[length];
if (source == null) {
for (int i = 0; i < length; i++) {
dst[i] = fillByte;
}
return dst;
}
try {
byte[] b = source.getBytes("UTF-8");
if (b.length > length) {
System.arraycopy(b, 0, dst, 0, length);
} else {
System.arraycopy(b, 0, dst, 0, b.length);
for (int i = dst.length; i < length; i++) {
dst[i] = fillByte;
}
}
} catch (Exception e) {
for (int i = 0; i < length; i++) {
dst[i] = fillByte;
}
}
return dst;
}
4.把string轉換成TLV編碼方式的字節數組流
public static byte[] UTF8string2TLVbytes(int tag,String value){
int length=value.length();
byte[] tag1=int2bytes(tag,4);
byte[] length1=int2bytes(length,4);
byte[] value1 = null;
try {
value1 = UTF8string2bytes(value,value.getBytes("UTF-8").length,(byte)0x00);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buff=pack(tag1,length1,value1);
return buff;
}
5.把字節流轉換成UTF-8字符串
public static String bytes2UTF8string(byte source[]) {
String dst = "";
try {
dst = (new String(source, "UTF-8"));
} catch (UnsupportedEncodingException e) {
dst = "";
}
return dst;
}
6.將字節流中的指定字節段轉換成UTF-8字符型
public static String bytes2UTF8string2(byte b[],int offset,int len){
byte[] a=new byte[len];
for (int i=0;i
a[i]=b[offset];
offset++;
}
return bytes2UTF8string(a);
}
7.字節流數據轉換成整型
public static int bytes2int(byte b[]) {
int s = 0;
for (int i = 0; i < b.length; i++) {
s = s | ((b[i] & 0xff) << ((b.length - i - 1) * 8));
}
return s;
}
8.將字節流中的指定字節段轉換成整型
public static int bytes2int2(byte b[],int offset,int len){
byte[] respcode=new byte[len];
for (int i=0;i
respcode[i]=b[offset];
offset++;
}
return bytes2int(respcode);
}
其中部分引用Java中Byte字節流處理的自定義方法庫1中設計的方法。
總結
以上是生活随笔為你收集整理的java byte(字节_【原创】Java中Byte字节流处理的自定义方法库2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 遇见你的猫物品怎么摆出与收起
- 下一篇: java 压缩汉字字节_java中计算汉