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 bytesToInt(byte[] src, int offset) {
|
int value;
|
value = (int) ((src[offset] & 0xFF)
|
| ((src[offset+1] & 0xFF)<<8)
|
| ((src[offset+2] & 0xFF)<<16)
|
| ((src[offset+3] & 0xFF)<<24));
|
return value;
|
}
|
}
|