I have String:
String str = "KITTEN";
And I would like to make a byte[] from it, but just:
byte[] mybyte = new byte[] { 'K', 'I', 'T', 'T', 'E', 'N'}
Anyone knows how to change String to that byte[]? Everything what I can find is about actual converting - please note that I don't want to have hex representation of string.
PS. Title of question may be wrong - I'm sorry for that, didn't know how to write it.
EDIT:
byte[] myBytes = str.getBytes();
Displaying:
byte[] display = new byte[] { 0x00, 0, 0, 'K', 'I', 'T'};
works, and displaying:
byte[] display = new byte[] { 0x00, 0, 0, myBytes[0], myBytes[1], myBytes[2] };
doesn't work. I try to display it on the screen of my device connected to the android phone by NFC. Do you know what's make the problem?
You are converting, and must convert - a char isn't the same as a byte.
You could use "ISO-8859-1" as the encoding to pass to String.getBytes(), which would get you a single byte per character, valid only for U+0000 to U+00FF (probably including characters in the "hole"; characters which aren't really in ISO-8859-1, but hey...) You'd get the ASCII representation of '?' for any characters not in that range though.
Wanting to do this is probably an indication that you've gone wrong earlier on though. In particular, if you're trying to get back some arbitrary binary data which you originally converted into a string without using base64 or something similar, you may well have already lost data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With