package com.mes.tools;
|
|
public class HexConversion {
|
/**
|
* @param a shuzi
|
* @return shuzu
|
*/
|
public static byte[] stringToInt(String a){
|
byte[] byt = new byte[a.length()/2];
|
for (int i = 0; i < a.length() - 1; i+=2) {
|
String output = a.substring(i, i + 2);
|
byt[i/2]=(byte)Integer.parseInt(output, 16);
|
}
|
return byt;
|
}
|
public static String byteToHexString(int bufSize,byte[] msg){
|
String tempHex = "";
|
String command = "";
|
if (bufSize != -1) {
|
for (int i = 0; i < bufSize; i++) {
|
tempHex = Integer.toHexString(msg[i] & 0xFF);
|
if (tempHex.length() == 1) {
|
tempHex = "0" + tempHex;
|
}
|
command += tempHex;
|
}
|
}
|
return command;
|
}
|
public static String intToHex(int number) {
|
return Integer.toHexString(number);
|
}
|
/**
|
* 将整数转换为4位16进制,如1转换为0001,10转换为000a
|
*
|
* @param number
|
* @return
|
*/
|
public static String intTo2ByteHex(int number) {
|
String numberHex = intToHex(number);
|
numberHex = String.format("%4s", numberHex).replace(' ', '0');
|
return numberHex;
|
}
|
/**
|
* 将整数转换为2位16进制,如1转换为01,10转换为0a
|
*
|
* @param
|
* @return
|
*/
|
public static String intTo1ByteHex(int number) {
|
String numberHex = intToHex(number);
|
numberHex = String.format("%2s", numberHex).replace(' ', '0');
|
return numberHex;
|
}
|
/**
|
* 从byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
|
*
|
* @param src: byte数组
|
* @param offset: 从数组的第offset位开始
|
* @return int数值
|
*/
|
public static int bytesToIntDesc(byte[] src, int offset) {
|
int value=0;
|
int length = src.length;
|
for(int i=0;i<length;i++){
|
value+=(int)((src[offset+i]&0xFF)<<(length-i-1)*8);
|
}
|
return value;
|
}
|
/**
|
* 将int数值转换为占size个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用
|
* @param value
|
* 要转换的int值
|
* @return byte数组
|
*/
|
public static byte[] intToBytesDesc( int value,int size )
|
{
|
byte[] src = new byte[size];
|
for(int i=0;i<size;i++){
|
src[i] = (byte) ((value>>(size-i-1)*8) & 0xFF);
|
}
|
return src;
|
}
|
/**
|
* 从byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
|
*
|
* @param src: byte数组
|
* @param offset: 从数组的第offset位开始
|
* @return int数值
|
*/
|
public static int bytesToInt(byte[] src, int offset) {
|
int value=0;
|
for(int i=0;i<src.length;i++){
|
value+=(int)((src[offset+i]&0xFF)<<i*8);
|
}
|
return value;
|
}
|
/**
|
* 将int数值转换为占size个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用
|
* @param value
|
* 要转换的int值
|
* @return byte数组
|
*/
|
public static byte[] intToBytes( int value,int size )
|
{
|
byte[] src = new byte[size];
|
for(int i=0;i<src.length;i++){
|
src[i] = (byte) ((value>>i*8) & 0xFF);
|
}
|
return src;
|
}
|
}
|