Question

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;
Was it helpful?

Solution

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

byte[] content = {0x42, 0x43, 0x41, 0x42, 0x43, 0x7E, 0x06, 0x02};

OTHER TIPS

Here you can forget about the hexadecimal notation, as the conversion is back and forth.

If you really mean the character 0xB0 (hex) or in other notation 176 decimal, you would do it as:

int c = 176;
content += Character.toChars(c);

As the string is encoded with Unicode thus might result in other bytes. As said in the comments, if you want byte values, use byte[] or better ByteArrayOutputStream, using write(176) and at the end toByteArray.


Explanation

In the ASCII range 0-127 Character.toChars give one char, represented in UTF-8 with one byte.

In the ISO-8859-* range 160-255 also one char, one byte. In the range 128-159 there reside mostly UTF-8 control characters, like in ASCII 0-32.

But some values are used for UTF-8 multi-byte encoding. Higher values 256-... might give one char (16bits) or several chars.

hexString = String.format ("%x", 176); 

is another option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top