本文介绍了转换十六进制字符串为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的一个字符串:

I've got a String like this:

init_thread = "2b11020000ed"

我要通过蓝牙发送此字符串,为我做到这一点:

I have to send this string via bluetooth, for what I do this:

byte[] init = init_thread.getBytes();
GlobalVar.mTransmission.write(init);

我需要的是定义的 init_thread 字符串是一个十六进制字符串将其转换为字节之前,因为如果我这样做的方式,它是得到了错误:

What I need is to define that the init_thread string is an hex string before converting it to bytes, because if I do this way, it is getting it wrong:

什么是现在正在做= 2(1字节),B(1字节),1(1个字节),1(1字节)...

What is doing now = 2(1byte), b(1byte), 1(1byte), 1(1byte)...

我们必须做的= 2B(1字节),11(1字节),02(1字节)...

What must do = 2b(1byte), 11(1byte), 02(1byte)...

推荐答案

转换为十六进制字节,字节十六进制。

Convert hex to byte and byte to hex.

public static byte[] hexStringToByteArray(String s) {
                int len = s.length();
                byte[] data = new byte[len/2];

                for(int i = 0; i < len; i+=2){
                    data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
                }

                return data;
            }

final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String byteArrayToHexString(byte[] bytes) {
            char[] hexChars = new char[bytes.length*2];
            int v;

            for(int j=0; j < bytes.length; j++) {
                v = bytes[j] & 0xFF;
                hexChars[j*2] = hexArray[v>>>4];
                hexChars[j*2 + 1] = hexArray[v & 0x0F];
            }

            return new String(hexChars);
        }

这篇关于转换十六进制字符串为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:18