Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal over 7F into String in Java

I need to append some hexadecimal characters to my string. I'm trying this:

content += Character.toString((char) Integer.parseInt(Integer.toHexString(originalSize).toString(), 16));

And it's working, but when originalSize is over 127 (7F in hex) it returns me two hexadecimal values.

For example, doing this:

content += Character.toString((char) Integer.parseInt(Integer.toHexString(176).toString(), 16));

The result is: (content hex numbers) C0 B0

B0 is 176 in hexadecimal, but I don't know how to remove C0. Any suggestions please? Thanks!

EDIT:

I want to send an string to a device via Bluetooth Low Energy. I have an string like this:

"ABCABC". In hexadecimal is 41 42 43 41 42 43.

Now, I want to add the format of this string (because the device is waiting for it), so I add it at the end: 41 42 43 41 42 43 7E 06 02, where:

  • 7E: beggining of the format
  • 06: number of chars
  • 02: specifical format given by manufacturer.

I have the main string and I'm adding this three hexadecimal characters by hand.

SOLUTION:

Based on Devon_C_Miller answer I found my own solution:

contentFormated = new byte[originalSize+3];

for(int i=0;i<originalSize;i++){
    contentFormated[i] = content.getBytes()[i];
}

contentFormated[originalSize] = 0x7E;
contentFormated[originalSize+1] = (byte) 0xB0;
contentFormated[originalSize+2] = 0x02;
like image 389
Fran Verona Avatar asked Nov 29 '25 16:11

Fran Verona


1 Answers

It sounds like you want a byte array rather than a String:

byte[] content = {0x42, 0x43, 0x41, 0x42, 0x43, 0x7E, 0x06, 0x02};
like image 192
Devon_C_Miller Avatar answered Dec 02 '25 06:12

Devon_C_Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!