android 进制转换方法
import android.util.Log;
public class CommandHelper {
public static String intToHexString(int value) {
String str = "";
if (value >= 0) {
str = Integer.toHexString(value);
} else {
str = Integer.toHexString((value & 0x000000FF) | 0xFFFFFF00)
.substring(6);
}
Log.d("SerialPort", "str = " + str);
if (str.length() == 1)
str = "0" + str;
str = str.toUpperCase();
return str;
}
public static String crcValue(String head, String id, String size,
String data) {
int value = 0;
if(null != size){
value = Integer.parseInt(head, 16) + Integer.parseInt(id, 16)
+ Integer.parseInt(size, 16) + dataValue(data);
} else {
value = Integer.parseInt(head, 16) + Integer.parseInt(id, 16)
+ dataValue(data);
}
Log.d("SerialPort", "value = " + value + " ~value = " + ~value);
return CommandHelper.intToHexString((~value) + 1);
}
public static int dataValue(String data) {
int result = 0;
for (int i = 0; i < data.length(); i = i + 2) {
result = result + Integer.parseInt(data.substring(i, i + 2), 16);
}
Log.d("SerialPort", "result = " + result);
return result;
}
public static String byteToHexString(byte[] data, int size) {
String receivedData = "";
for (int i = 0; i < size; i++) {
String hex = Integer.toHexString(data[i] & 0xff);
if (hex.length() == 1)
hex = \'0\' + hex;
receivedData += hex.toUpperCase();
}
return receivedData;
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals(""))
return null;
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
// Log.d("AppsActivity", "d " + i + " = " + d[i]);
}
return d;
}
public static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static BaseCommand parseStringToBaseCommand(String data) {
if (null == data || data.length() < CommandUtil.COMMAND_LEAST_LENGTH) {
return null;
}
int length = data.length();
BaseCommand cmd = new BaseCommand();
cmd.setHead(CommandUtil.HEAD_READ);
cmd.setId(data.substring(2, 4));
cmd.setData(data.substring(6, length - 2));
cmd.setCrc(data.substring(length - 2, length));
return cmd;
}
}