经常需要与plc,单片机,传感器通讯,需要解析设备数据,java跟C不同,需要二进制转换成java的数据,因此整理了一个工具,共享出来,欢迎大家来指正。
public class ByteTool {
public static byte[] IntToByte(int v)
{
//System.out.print("int value="+v);
byte[] arr=new byte[4];
arr[0]=(byte)(v&0x000000ff);
v>>=8;//右移8位
arr[1]=(byte)(v&0x000000ff);
v>>=8;//右移8位
arr[2]=(byte)(v&0x000000ff);
v>>=8;//右移8位
arr[3]=(byte)(v&0x000000ff);
return arr;
}
public static byte[] ShortToByte(short v)
{
byte[] arr=new byte[2];
arr[0]=(byte)(v&0x00ff);
v>>=8;//锟斤拷锟斤拷8位
arr[1]=(byte)(v&0x00ff);
return arr;
}
public static String arrToString(byte [] cmd,int len) {
StringBuffer sb=new StringBuffer();
for(int i=0;i
return sb.toString();
}
public static byte[] stringToArray(String s) {
byte[] arr=new byte[s.length()/2];
int t=0;
for(int i=0;i
char b=s.charAt(i+1);
arr[t]=(byte)(hexToInt(a)*16+hexToInt(b));
t++;
}
return arr;
}
private static int hexToInt(char a) {
if(a>='0' && a<='9')return (int)(a-'0');
if(a>='A' && a<='Z') return 10+(a-'A');
//System.out.println("charvalue = "+a);
return 0;
}
public static String byteToString(byte b) {
StringBuffer sb=new StringBuffer();
byte a=0x01;
for(int i=0;i<8;i++) {
if(0== (a&b)) {
sb.insert(0, "0");
}
else {
sb.insert(0, "1");
}
a<<=1;//左移1位
}
return sb.toString();
}
public static int byteArrayToInt2(byte[] data,int start) {
int value=0;
for(int i = start; i < start+4; i++) {
int shift= i * 8;
value +=(data[i] & 0xFF) << shift;
}
return value;
}
public static int byteArrayToInt(byte[] data,int start) {
int value=0;
for(int i = start; i < start+4; i++) {
int shift= (start+3-i) * 8;
value +=(data[i] & 0xFF) << shift;
}
return value;
}
public static short byteArrayToShort(byte[] bytes,int start)
{
short v=0;
v=(short)((bytes[start]&0xff)<<8 | bytes[start+1]&0xff);//温度11-12位
return v;
}
public static float getFloat(byte[] arr, int index) {
ByteBuffer buf=ByteBuffer.allocateDirect(4);
buf.put(arr,index,4);
buf=buf.order(ByteOrder.LITTLE_ENDIAN);//方向转换
buf.rewind();
float f=buf.getFloat();
return f;
}
public static float getFloat2(byte[] arr, int index) {
ByteBuffer buf=ByteBuffer.allocateDirect(4);
buf.put(arr,index,4);
buf=buf.order(ByteOrder.BIG_ENDIAN);//方向转换
buf.rewind();
float f=buf.getFloat();
return f;
}
}



