[英]How can I receive to socket input as hexadecimal?
我發送了一個帶套接字的GET消息。 我收到了作為字符串的響應消息。 但我希望以十六進制的形式收到。 但我沒有完成。 這是我的代碼塊作為字符串。 你能幫助我嗎 ?
dos = new DataOutputStream(socket.getOutputStream());
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
dos.write(requestMessage.getBytes());
String data = "";
StringBuilder sb = new StringBuilder();
while ((data = dis.readLine()) != null) {
sb.append(data);
}
當你使用BufferedReader
你將獲得String
格式的輸入。所以更好的方式使用InputStream
...
這是實現此目的的示例代碼。
InputStream in = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] read = new byte[1024];
int len;
while((len = in.read(read)) > -1) {
baos.write(read, 0, len);
}
// this is the final byte array which contains the data
// read from Socket
byte[] bytes = baos.toByteArray();
獲取byte[]
您可以使用以下函數將其轉換為十六進制字符串
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());// here sb is hexadecimal string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.