編輯:關於 Android 程式設計
想起前段時間做的物聯網外包專案,經常需要處理透過WiFi接收的資料:有時要轉成十六進制字串,有時又要還原成十進制數據,一切都依照雙方約定的協議來進行。同理,我們發送出去的資料也需要經過特殊轉換成byte字節,這樣硬體那端收到時才不會是一團亂碼。
原始數據示例:68 38 38 68 ... 0C 3B 78 34 12 0C ... 02 FD 17 00 CS 16
Android讀到的則是byte字節數組:
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte readBuffer[] = new byte[64];
int count = 0;
try {
count = dis.read(readBuffer);
} catch (IOException e) {
continue;
}
readBuffer收到的數據是這樣的:104, 56, 56, 104, 0, 114, 120, 85, 52, 18, 67, 35, 1, 7, 0, 0, 0, 0, 12, 19, 120, 86, 52, 18, ... , -3, 23, 0, 0, 22
如果直接把這個字節數組轉成String字串,那肯定是亂碼,因為硬體發過來的是十六進制數據。把readBuffer轉換成十六進制字串後會變成:68, 38, 38, 68, 00, 72, 78, 55, 34, 12, 43, 23, 01, 07, 00, 00, 00, 00, 0C, 13, 78, 56, 34, 12, ... 可以看出這才和硬體實際發送的內容一致。其中原本非十六進制的Y、CS等佔位則用00填充。這些都必須依據雙方收發協議來解析處理。
Android的原始數據形如:68 04 04 68 35 FD 50 00 A0 16,同樣是十六進制字串,需要做的就是把它轉換成byte數組:
private String mstrRestartSend = "FE FE 68 04 04 68 53 FD 50 00 A0 16";
private byte[] mRestart = null;
mRestart = StringUtil.HexCommandtoByte(mstrRestartSend.getBytes());
public class StringUtil {
// 十六進制字串轉換成byte數組
public static byte[] HexCommandtoByte(byte[] data) {
if (data == null) {
return null;
}
int nLength = data.length;
String strTemString = new String(data, 0, nLength);
String[] strings = strTemString.split(" ");
nLength = strings.length;
data = new byte[nLength];
for (int i = 0; i < nLength; i++) {
if (strings[i].length() != 2) {
data[i] = 00;
continue;
}
try {
data[i] = (byte) Integer.parseInt(strings[i], 16);
} catch (Exception e) {
data[i] = 00;
continue;
}
}
return data;
}
}
這樣發送過去就不會出錯或亂碼了。很多初學者,尤其是在物聯網開發中,往往搞不清楚這個最基本的資料交流轉換。
示例圖:

以下彙整了Java中二進制、十進制、十六進制與ASCII碼,以及字節數組與十六進制字串之間相互轉換的常用方法:
public class DigitalTrans {
/** 數字字串轉ASCII碼字串 */
public static String StringToAsciiString(String content) {
String result = "";
int max = content.length();
for (int i = 0; i < max; i++) {
char c = content.charAt(i);
result = result + Integer.toHexString(c);
}
return result;
}
/** 十六進制轉字串(encodeType:4為Unicode,2為普通編碼) */
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char) hexStringToAlgorism(
hexString.substring(i * encodeType, (i + 1) * encodeType));
result += c;
}
return result;
}
/** 十六進制字串轉十進制 */
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = (c >= '0' && c <= '9') ? c - '0' : c - 55;
result += Math.pow(16, max - i) * algorism;
}
return result;
}
/** 十六轉二進制 */
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
switch (hex.charAt(i)) {
case '0': result += "0000"; break;
case '1': result += "0001"; break;
case '2': result += "0010"; break;
case '3': result += "0011"; break;
case '4': result += "0100"; break;
case '5': result += "0101"; break;
case '6': result += "0110"; break;
case '7': result += "0111"; break;
case '8': result += "1000"; break;
case '9': result += "1001"; break;
case 'A': result += "1010"; break;
case 'B': result += "1011"; break;
case 'C': result += "1100"; break;
case 'D': result += "1101"; break;
case 'E': result += "1110"; break;
case 'F': result += "1111"; break;
}
}
return result;
}
/** 二進制字串轉十進制 */
public static int binaryToAlgorism(String binary) {
int max = binary.length();
int result = 0;
for (int i = max; i > 0; i--) {
int algorism = binary.charAt(i - 1) - '0';
result += Math.pow(2, max - i) * algorism;
}
return result;
}
/** 十進制轉十六進制字串 */
public static String algorismToHEXString(int algorism) {
String result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
return result.toUpperCase();
}
/** 字節數組轉為普通字串(ASCII對應字符) */
public static String bytetoString(byte[] bytearray) {
String result = "";
for (byte b : bytearray) {
result += (char) b;
}
return result;
}
/** 十六進制字串轉為Byte數組,每兩個字符轉為一個Byte */
public static byte[] hexStringToByte(String hex) {
int max = hex.length() / 2;
byte[] bytes = new byte[max];
String binarys = hexStringToBinary(hex);
for (int i = 0; i < max; i++) {
bytes[i] = (byte) binaryToAlgorism(binarys.substring(i * 8 + 1, (i + 1) * 8));
if (binarys.charAt(8 * i) == '1') {
bytes[i] = (byte) (0 - bytes[i]);
}
}
return bytes;
}
/** 十六進制串轉化為byte數組 */
public static final byte[] hex2byte(String hex) throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException();
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = (byte) byteint;
}
return b;
}
/** 字節數組轉換為十六進制字串 */
public static final String byte2hex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException("Argument b ( byte array ) is null!");
}
String hs = "";
String stmp;
for (byte value : b) {
stmp = Integer.toHexString(value & 0xff);
if (stmp.length() == 1) {
hs += "0" + stmp;
} else {
hs += stmp;
}
}
return hs.toUpperCase();
}
}
掌握這套轉換邏輯,就能在Android與硬體之間穩定、準確地交換數據,避免解析出錯。這些看似瑣碎的底層轉換,恰恰是物聯網通訊中最容易出問題、也最需要紮實掌握的基本功。
Android Design 解讀:Android 4.0 帶來的設計新里程碑
想成為一名出色的 Android 開發工程師,怎麼能不懂 Android 的設計規範呢?自從 Android 4.0 問世後,Google 為 Android 開發者制定
Android 應用多語言切換:Locale 與介面刷新
多語言是許多應用的基本需求。Android 可透過不同 values 資料夾放置各語言的 string.xml,再利用 Configuration 的 locale 屬性
自製 ClearEditText:為 Android 輸入框加上一鍵清除功能
這次要分享一個實用的小元件 ClearEditText:在 Android 輸入框右側放上一個小圖示,點一下就能清空輸入內容。iOS 只要設定某個屬性就能做到,但 And
Mac 開發 Android 環境搭建步驟圖解
準備 Java JDK 在 Mac 上開發 Android,第一步通常是準備 Java JDK。部分系統版本可能預設包含舊版 JDK,但為了開發相容性,建議安裝明確的 J