socket 傳送接收16進製制資料

2021-10-04 03:16:10 字數 2602 閱讀 2920

背景:做了個智慧型櫃管理系統,需要和智慧型櫃對接。互動使用的是socket。

轉換邏輯:

傳送規則:資料(1)---->16進製制(0x01)---->高4位(0x00)、低四位(0x01)---->10進製(0、1)---->ansi碼(48,49)---->16進製制(0x30,0x31)---->傳送

ansi如圖

傳送接收資料:start為碼頭,end為碼尾加驗證。是和第三方溝通的標誌。

/**

* 傳送指令

* @param ip 智慧型櫃ip位址

* @param com 指令型別

* @param data 資料

* @return

*/public static string sendsocket(string ip,byte com,byte data)

outputstream.write(end);

socket.shutdownoutput();

//獲取乙個輸入流,接收服務端的資訊

inputstream inputstream=socket.getinputstream();

bufferedinputstream bis = new bufferedinputstream(inputstream);

datainputstream dis = new datainputstream(bis);

byte bytes = new byte[1];

string ret = "";

byte result = new byte[1024];

int i = 0;

while (dis.read(bytes) != -1)

system.out.println(ret);

//關閉相對應的資源

dis.close();

inputstream.close();

outputstream.close();

socket.close();

return ret;

}catch (exception e)

}/**

* 將接收到的資料轉換為16進製制

* @param bytes

* @return

*/public static string bytestohexstring(byte bytes)

}return sb.tostring();

}

步驟:傳遞乙個數後獲取高4位height,低4位low。在根據ansi陣列獲取值

/**

* 0-f 0x30,0x46

*/public static byte ansi = new byte;

/**

* 將乙個integer值轉換成兩個0***的字串。integer要小於255.

* @param code

* @return

*/public static byte transfer(integer code)

int height = ((code & 0xf0) >> 4);

int low = (code & 0x0f);

byte b = new byte[2];

b[0] = ansi[height];

b[1] = ansi[low];

return b;

}

接收資料:33 32----> 3,2 ---->0x32 ---->2

private static final string hexstr = "0123456789abcdef";

private static mapgetmap()else}}

return map;

}

將獲取到的資料(33 32)按照空格分開

string str = res.split(" ");
兩兩合併生成byte陣列。

byte b = new byte[17];

for(int i=0;i<17;i++)

業務需要,乙個byte位代表8個箱門狀態,0-開,1-關

mapgoodsmap = new hashmap<>();

goodsmap.put("1",(b&0x01)==0x01?1:0);

goodsmap.put("2",(b&0x02)==0x02?1:0);

goodsmap.put("3",(b&0x04)==0x04?1:0);

goodsmap.put("4",(b&0x08)==0x08?1:0);

goodsmap.put("5",(b&0x10)==0x10?1:0);

goodsmap.put("6",(b&0x20)==0x20?1:0);

goodsmap.put("7",(b&0x40)==0x40?1:0);

goodsmap.put("8",(b&0x80)==0x80?1:0);

socket傳送和接收資料

1 sendbuf sendtext sendstream 幾乎所有的通訊控制項都會提供上面的3個方法。首先看看sendbuf function tcustomwinsocket.sendbuf var buf count integer integer varerrorcode integer b...

16進製制位址進製

16進製制 1,2,3,4,5,6,7,8,9,a,b,c,d,e,f 乙個位址表示乙個byte,即8bit 0x8000000033221100 77665544 bbaa9988 ffeeddcc 0x8000001076543210 0x80000000 00000000 0x80000001...

UIColor的16進製制色值,16進製制字串擴充套件

inte ce uicolor hex 16進製制字串轉化為顏色 param hexstr 16進製制字串 支援 0x.0x.return uicolor uicolor colorwithhexstring nsstring hexstr 16進製制字串轉化為顏色 param hexstr 16進...