Convert hex string to byte [] - android

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);
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:
What is doing now = 2(1byte), b(1byte), 1(1byte), 1(1byte)...
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);
}

If we want to convert hex to byte array, we should make sure that hex string length should be of even length. Below method handles this
public static byte[] hexToByteArray(String hex) {
hex = hex.length()%2 != 0?"0"+hex:hex;
byte[] b = new byte[hex.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(hex.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}

Related

How to send hex value to BLE device?

I am developing one ble application in which as an input I have to give BLE a hex value as a time parameter so that the device will run for that much time. I have tried everything I know but it is not working. Please help me to get a solution.
AppConstants.pulse_time.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
AppConstants.gatt.setCharacteristicNotification(AppConstants.pulse_time, true);
// AppConstants.pulse_time.setValue(3, BluetoothGattCharacteristic.FORMAT_UINT16, 0);
// AppConstants.pulse_time.setValue(toBytes(03));
// AppConstants.pulse_time.setValue(toHex(""+3));
// AppConstants.pulse_time.setValue("0x2");
// AppConstants.pulse_time.setValue(convertStringToHex("32"));
AppConstants.pulse_time.setValue("0x"+ Integer.toHexString(2));
// AppConstants.pulse_time.setValue(String.format("%02x","2"));
// AppConstants.pulse_time.setValue(Integer.toString(2, 16));
// AppConstants.pulse_time.setValue(hexStringToByteArray("0x2"));
// AppConstants.pulse_time.setValue(31,BluetoothGattCharacteristic.FORMAT_UINT8,0);
// AppConstants.pulse_time.setValue(toBytes(3));
AppConstants.gatt.writeCharacteristic(AppConstants.pulse_time);
private String convertStringToHex(String string)
{
StringBuilder newString = new StringBuilder();
for (int i=0; i<string.length(); i++)
{
newString.append(String.format("%02X ", (byte)(string.charAt(i))));
}
return newString.toString();
}
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;
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
Good evening, could you please explain more fine-grained which kind of "hex"-value the result should be? You need both functions, for converting between string and hex (hex-number)?
If the code is Java, then refer:
public static int convert(int n) {
return Integer.valueOf(String.valueOf(n), 16);
}
or:
Integer.toHexString(int)
I know this is just an integer, not a string. Please explain more, what "AppConstants.pulse_time.setValue" expects as parameter.

how to format thermal printer in android using byte?

I want to know how the byte code work in thermal printer
tcmd = new byte[7];
tcmd[0] = 0x1B;
tcmd[1] = 0x5A;
tcmd[2] = 0x00;
tcmd[3] = 0x02;
tcmd[4] = 0x07;
tcmd[5] = 0x17;
tcmd[6] = 0x00;
String content = "SDK 2D-Code print test.";
wfComm.sndByte(tcmd);
wfComm.sendMsg(content, "GBK");
this code send the data to printer and the printer print the qr code that has the string , but if i send this without the byte array the printer simply print the string.
I want to understand the byte code if you can give me the documentation in which show that how this byte work
Check this image
The code is tested and verified..it will convert qr code to byte and print it in paper.just create utils class as described below and call this method..
byte[] command = Utils.decodeBitmap(bitmap);
mService.write(command);
public class Utils {
// UNICODE 0x23 = #
public static final byte[] UNICODE_TEXT = new byte[] {0x23, 0x23, 0x23,
0x23, 0x23, 0x23,0x23, 0x23, 0x23,0x23, 0x23, 0x23,0x23, 0x23, 0x23,
0x23, 0x23, 0x23,0x23, 0x23, 0x23,0x23, 0x23, 0x23,0x23, 0x23, 0x23,
0x23, 0x23, 0x23};
private static String hexStr = "0123456789ABCDEF";
private static String[] binaryArray = { "0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };
public static byte[] decodeBitmap(Bitmap bmp){
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
List<String> list = new ArrayList<String>(); //binaryString list
StringBuffer sb;
int bitLen = bmpWidth / 8;
int zeroCount = bmpWidth % 8;
String zeroStr = "";
if (zeroCount > 0) {
bitLen = bmpWidth / 8 + 1;
for (int i = 0; i < (8 - zeroCount); i++) {
zeroStr = zeroStr + "0";
}
}
for (int i = 0; i < bmpHeight; i++) {
sb = new StringBuffer();
for (int j = 0; j < bmpWidth; j++) {
int color = bmp.getPixel(j, i);
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = color & 0xff;
// if color close to white,bit='0', else bit='1'
if (r > 160 && g > 160 && b > 160)
sb.append("0");
else
sb.append("1");
}
if (zeroCount > 0) {
sb.append(zeroStr);
}
list.add(sb.toString());
}
List<String> bmpHexList = binaryListToHexStringList(list);
String commandHexString = "1D763000";
String widthHexString = Integer
.toHexString(bmpWidth % 8 == 0 ? bmpWidth / 8
: (bmpWidth / 8 + 1) );
if (widthHexString.length() > 2) {
Log.e("decodeBitmap error", " width is too large");
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString = widthHexString + "00";
String heightHexString = Integer.toHexString(bmpHeight);
if (heightHexString.length() > 2) {
Log.e("decodeBitmap error", " height is too large");
return null;
}
else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString = heightHexString + "00";
List<String> commandList = new ArrayList<String>();
commandList.add(commandHexString+widthHexString+heightHexString);
commandList.addAll(bmpHexList);
return hexList2Byte(commandList);
}
public static List<String> binaryListToHexStringList(List<String> list) {
List<String> hexList = new ArrayList<String>();
for (String binaryStr : list) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
String hexString = myBinaryStrToHexString(str);
sb.append(hexString);
}
hexList.add(sb.toString());
}
return hexList;
}
public static String myBinaryStrToHexString(String binaryStr) {
String hex = "";
String f4 = binaryStr.substring(0, 4);
String b4 = binaryStr.substring(4, 8);
for (int i = 0; i < binaryArray.length; i++) {
if (f4.equals(binaryArray[i]))
hex += hexStr.substring(i, i + 1);
}
for (int i = 0; i < binaryArray.length; i++) {
if (b4.equals(binaryArray[i]))
hex += hexStr.substring(i, i + 1);
}
return hex;
}
public static byte[] hexList2Byte(List<String> list) {
List<byte[]> commandList = new ArrayList<byte[]>();
for (String hexStr : list) {
commandList.add(hexStringToBytes(hexStr));
}
byte[] bytes = sysCopy(commandList);
return bytes;
}
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]));
}
return d;
}
public static byte[] sysCopy(List<byte[]> srcArrays) {
int len = 0;
for (byte[] srcArray : srcArrays) {
len += srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray : srcArrays) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}
return destArray;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}}

How to aproach this in android? signed byte

I have a piece of problem that I want to achieve in android.
The formula is
Server Seed + Client Seed (->byte[4]) + Bet Number (->byte[4])
Double SHA2-512 hash the result
Keep taking groups of 3 bytes and converting to an integer, until a value less than 16 million is found. If you run out of bytes, hash it
again and start over.
Find the value's modulus of 1 million
The modulus is the bet result!
Which have an example code in C#
static bool VerifyBetResult(string serverSeed, int clientSeed, int betNumber,
long betResult, string serverSeedHash = null)
{
Func<string, byte[]> strtobytes = s => Enumerable
.Range(0, s.Length / 2)
.Select(x => byte.Parse(s.Substring(x * 2, 2), NumberStyles.HexNumber))
.ToArray();
byte[] server = strtobytes(serverSeed);
byte[] client = BitConverter.GetBytes(clientSeed).Reverse().ToArray();
byte[] num = BitConverter.GetBytes(betNumber).Reverse().ToArray();
byte[] serverhash = serverSeedHash == null ? null : strtobytes(serverSeedHash);
byte[] data = server.Concat(client).Concat(num).ToArray();
using (SHA512 sha512 = new SHA512Managed())
{
if (serverhash != null)
using (SHA256 sha256 = new SHA256Managed())
if (!sha256.ComputeHash(server).SequenceEqual(serverhash))
throw new Exception("Server seed hash does not match server seed");
byte[] hash = sha512.ComputeHash(sha512.ComputeHash(data));
while (true)
{
for (int x = 0; x <= 61; x += 3)
{
long result = (hash[x] << 16) | (hash[x + 1] << 8) | hash[x + 2];
if (result < 16000000)
return result % 1000000 == betResult;
}
hash = sha512.ComputeHash(hash);
}
}
}
Using these values
serverSeed = e600f76aa6c520dff7db34559bd05cb1048b1830a07cd81844147a19048fc9be;
clientSeed = 443944;
betNumber = 0;
serverHash = ca90022ac66a6a77d8b5072e101bff505c2bff552b1b9a0785f0c438d5b6228f;
I want to find the (result % 1000000) which should be = 563383
But I got -25564 and the serverHash does not match the serverSeed when hashing the seed to sha256
Update
This is my code:
private byte[] reverse(byte[] b){
int i = b.length - 1;
byte newB[] = new byte[4];
for(int x = 0; x < b.length; x++){
newB[x] = b[i];
i--;
}
return newB;
}
private byte[] strToByte(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;
}
private long verifyBet(){
//MessageDigest md256 = null;
MessageDigest md512 = null;
try {
//md256 = MessageDigest.getInstance("SHA-256");
md512 = MessageDigest.getInstance("SHA-512");
} catch (Exception e) {
e.printStackTrace();
}
String //res = "ServerSeed = ",
sSeed = "e600f76aa6c520dff7db34559bd05cb1048b1830a07cd81844147a19048fc9be";
//sHash = "ca90022ac66a6a77d8b5072e101bff505c2bff552b1b9a0785f0c438d5b6228f";
int cSeed = 443944,
num = 0;
byte serverSeed[] = strToByte(sSeed),
//serverHash[] = strToByte(sHash),
clientSeed[] = reverse(ByteBuffer.allocate(4).putInt(cSeed).array()),
betNumber[] = reverse(ByteBuffer.allocate(4).putInt(num).array());
byte data[] = ByteBuffer.allocate(serverSeed.length + clientSeed.length + betNumber.length)
.put(serverSeed).put(clientSeed).put(betNumber).array();
data = md512.digest(data);
data = md512.digest(data);
long secret = 0;
boolean found = false;
while(!found){
for(int x = 0; x <= 61; x += 3){
long result = (data[x] << 16 | data[x+1] << 8) | data[x+2];
if (result < 16000000){
secret = result % 1000000;
found = true;
}
}
data = md512.digest(data);
}
return secret;
}
After much more research I found that byte in java is signed while the code I am basing from is calculating in unsigned byte which is why I am getting result in negative..
How can I get set of bytes in 'unsigned' form?
After so much research and testing. I finally got it. This is the code.
private byte[] strToByte(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;
}
private long verifyBet(int _num){
MessageDigest md512 = null;
try {
md512 = MessageDigest.getInstance("SHA-512");
} catch (Exception e) {
e.printStackTrace();
}
String sSeed = "e600f76aa6c520dff7db34559bd05cb1048b1830a07cd81844147a19048fc9be";
int cSeed = 443944,
num = _num;
byte serverSeed[] = strToByte(sSeed),
clientSeed[] = ByteBuffer.allocate(4).putInt(cSeed).array(),
betNumber[] = ByteBuffer.allocate(4).putInt(num).array();
byte data[] = ByteBuffer.allocate(serverSeed.length + clientSeed.length + betNumber.length)
.put(serverSeed).put(clientSeed).put(betNumber).array();
data = md512.digest(data);
data = md512.digest(data);
long secret = 0;
boolean found = false;
while(!found){
for(int x = 0; x <= 61; x += 3){
long result = ((data[x] & 0xFF) << 16 | (data[x+1] & 0xFF) << 8) | data[x+2] & 0xFF;
if (result < 16000000){
secret = result % 1000000;
found = true;
x = 62;
}
}
data = md512.digest(data);
}
return secret;
}

How to restore base64 encoded opencv java matrix to C++ cv::Mat?

I'm extracting ORB descriptors of an image in android using opencv which is then sent to a C++ server using a socket. To send it via the socket I'm encoding the opencv mat of descriptors to base64 using the below java code.
public static String matToJson(Mat mat){
JsonObject obj = new JsonObject();
if(mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
mat.get(0, 0, data);
obj.addProperty("rows", mat.rows());
obj.addProperty("cols", mat.cols());
obj.addProperty("type", mat.type());
// We cannot set binary data to a json object, so:
// Encoding data byte array to Base64.
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
obj.addProperty("data", dataString);
Gson gson = new Gson();
String json = gson.toJson(obj);
return json;
} else {
Log.e(TAG, "Mat not continuous.");
}
public static Mat matFromJson(String json){
JsonParser parser = new JsonParser();
JsonObject JsonObject = parser.parse(json).getAsJsonObject();
int rows = JsonObject.get("rows").getAsInt();
int cols = JsonObject.get("cols").getAsInt();
int type = JsonObject.get("type").getAsInt();
String dataString = JsonObject.get("data").getAsString();
byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);
Mat mat = new Mat(rows, cols, type);
mat.put(0, 0, data);
return mat;
}
The output from matToJson() looks like below:
{"rows":26,"cols":32,"type":0,"data":"aSbt5TQabzJ9qv7s3ymQchrEf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Dtr2jPZqzR42MDCIA\u003d\u003d\n"}
the encoded base64 string in the "data" key is the Matrix data.
The above json string is sent to the server via socket.
Now, I need to convert the "data" value of the json string back to cv::Mat in C++, so how do i get back the matrix from the above base64 string ?
Assuming that you read the data from the JSON, you can create the Mat like this:
int rows = 26;
int cols = 32;
int type = 0;
string data = "aSbt5TQabz...";
string decoded_data = base64_decode(data);
Mat m(rows, cols, type, (void*)decoded_data.data());
Code for base64_decode is from here
NOTE
I needed to manually convert the characted \u003D to = to make it work. You can avoid to escape HTML characters using Gson gson = new GsonBuilder().disableHtmlEscaping().create();. See here.
Code:
#include <opencv2\opencv.hpp>
#include <vector>
#include <string>
using namespace std;
using namespace cv;
// Code from: http://www.adp-gmbh.ch/cpp/common/base64.html
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i == 4) {
for (i = 0; i < 4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++)
char_array_4[j] = 0;
for (j = 0; j < 4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
int main()
{
// Read your JSON here...
int rows = 26;
int cols = 32;
int type = 0;
//string data(L"aSbt5TQabzJ9qv7s3ymQchrEfSyp8OWO5v8nkG6oUiFAMLFkAExBEGCgJggSF0AyAFRoCAlgsADJ\niAUwQCBGImQwuWSATEEQYrAiCNY3QToBVGgYAWDxAMmIRTTAYEYibDS4YqltU5o7v68Y3/9JOpHX\n/RAaZvsiy991f8JzxnNJJ33lNB5vMn3ofkzfP5BwlkR/LKnw4c7n/yOQTuhTcUAwOWAATFEQYCAg\nCBYXADCAFFAIAWCwAMGJADBAAEYyYCAxQABNQQBgpCQIFhdAMgBUQAgAYLAAwYgBMEACRiJgMLFk\nAEhBAGKkJAgWF0AyAVRIGABgsADJiAUwwABGImwwuXW4bVGaM/+mGJ+3QTqV3v0YK3b5As/fNX3A\n4EZzQTCRZABMRQBgoiIIVjdAMgBUaBgBYLEAyagFMMBgRiJJPj33NJ57N33ofky/O5Bwhi5+DKm4\n4e7n/zKQSojDKXw0vHW4b1Gas7+2GNc3QzuF33wYKGT5AMvbdTTA8EZzQCCRZABIAQBgoCIIFhdA\nMgBUaBgBYKAAiYAFMEBgRiBpLv33NI9pN30p/1z/KZBwgqZ8DLn44S7G/zKQSoDDKUAhEUAQSEEA\nYAAgCBYXADAQVEBAASCgACGIABBAAEYgdDC8dahsURLiv7YYlzdAOofWfRiLRfsAy8t1NODgRnNA\nIJFEAEgAAGCgIAgWE0AyAFRIAABgoACJgAUwQCBGIEAikEQgCAACYKggaBITwDIAVEwAAGCAAImA\nJTBAIAIhYDC5dGhtURJzvzYYl7dAOofWfRgLePMA34t1cODARnNAIBFAEEgAAGAAIAgSEwAwEFxA\nYEEggAwhiAAQQAJGIHEy1WQoDEEQ4KiyTJcTwDIExGwMiWHRAMCpIb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A\nYEEggAwhiAAQQAJGIHEy1WQoDEEQ4KiyTJcTwDIExGwMiWHRAMCpIbBogEIhcapb+iytSRfzGbNY\nt4PQeEuubByba8Ix2vkwWOiIwil4oLhwie1RjqK3rhiXtUIagdbsEBpr4wDb5XV54EDGYnAwuXSI\nbVEb4rekGBe3QDoB1mwYGm/6EtundT3g4MZicaBb+qytSZb+GbFct8PYeKGObBybbdox2ekyePiB\nwij1oBl6rKxJm/IRoVi300g4gYpsHDtr2jPZqzR42MDCIA==\n";
string decoded_data = base64_decode(data);
Mat m(rows, cols, type, (void*)decoded_data.data());
cout << m << endl;
return 0;
}

How to covert String to byte for BLE mBluetoothGatt.writeCharacteristic?

I am developing in Android BLE.
I try to send string to BLE device(like TI CC2541) , and it seems can not send string direct to BLE device.
It need to convert the String to Byte.
I have search some information , there has someone use URLEncoder.encode.
But I am not sure which is the answer what I need.
But how to convert the String to Byte?
The following code is writeCharacteristic for BLE
public void writeString(String text) {
// TODO Auto-generated method stub
BluetoothGattService HelloService = mBluetoothGatt.getService(HELLO_SERVICE_UUID);
BluetoothGattCharacteristic StringCharacteristic = HelloService.getCharacteristic(UUID_HELLO_CHARACTERISTIC_WRITE_STRING);
mBluetoothGatt.setCharacteristicNotification(StringCharacteristic , true);
int A = Integer.parseInt(text);
//How to convert the String to Byte here and set the Byte to setValue ?????
StringCharacteristic .setValue(A, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
mBluetoothGatt.writeCharacteristic(StringCharacteristic );
Log.d(TAG, "StepCount Characteristic End!");
}
How to convert the String to Byte?
Where you get your String:
byte[] strBytes = text.getBytes();
byte[] bytes = context.yourmWriteCharacteristic.getValue();
Please add a null check too like:
if (bytes == null) {
Log.w("Cannot get Values from mWriteCharacteristic.");
dismiss();// equivalent action
}
if (bytes.length <= strBytes.length) {
for(int i = 0; i < bytes.length; i++) {
bytes[i] = strBytes[i];
}
} else {
for (int i = 0; i < strBytes.length; i++) {
bytes[i] = strBytes[i];
}
}
Now, something like:
StepCount_Characteristic.setValue(bytes);
mBluetoothGatt.writeCharacteristic(StepCount_Characteristic);
I found the following code help me convert the string.
private byte[] parseHex(String hexString) {
hexString = hexString.replaceAll("\\s", "").toUpperCase();
String filtered = new String();
for(int i = 0; i != hexString.length(); ++i) {
if (hexVal(hexString.charAt(i)) != -1)
filtered += hexString.charAt(i);
}
if (filtered.length() % 2 != 0) {
char last = filtered.charAt(filtered.length() - 1);
filtered = filtered.substring(0, filtered.length() - 1) + '0' + last;
}
return hexStringToByteArray(filtered);
}
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;
}
private int hexVal(char ch) {
return Character.digit(ch, 16);
}
If you want to convert string value. you just need to call like the following:
String text;
byte[] value = parseHex(text);

Categories

Resources