80,351
社区成员
发帖
与我相关
我的任务
分享
public int unsignCharToInt(byte[] res) {
DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(res));
int a = 0;
try {
a = dataInputStream.readUnsignedByte();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
public class TestByte {
public static void main(String[] args) {
byte[] bytes = new byte[]{(byte) 0xff};
int i = unsignCharToInt(bytes);
System.out.println("result:" + i + " ,byteToStr:" + byteToStr(bytes));
}
public static int unsignCharToInt(byte[] res) {
DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(res));
int a = 0;
try {
a = dataInputStream.readUnsignedByte();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
public static String byteToStr(byte[] a) {
StringBuilder sb = new StringBuilder("");
if (a == null || a.length == 0) {
return "";
}
for (int i = 0; i < a.length; i++) {
sb.append(Integer.toHexString((a[i] >>> 4) & 0x0F).toUpperCase());
sb.append(Integer.toHexString(a[i] & 0x0F).toUpperCase());
}
return sb.toString();
}
}
运行结果:result:255 ,byteToStr:FF
public static int toInt(byte[] bytes){
int number = 0;
for(int i = 0; i < 4 ; i++){
number += bytes[i] << i*8;
}
return number;
}
public String byteToStr(byte[] a) {
StringBuffer sb = new StringBuffer("");
if (a == null || a.length == 0) {
return "";
}
for (int i = 0; i < a.length; i++) {
sb.append(Integer.toHexString((a[i] >>> 4) & 0x0F).toUpperCase());
sb.append(Integer.toHexString(a[i] & 0x0F).toUpperCase());
}
return sb.toString();
}
我用这个函数打印
Log.d("DevMsg",byteToStr(Arrays.copyOfRange(msg,6,7)));
打印的结果是"FF"