I’m trying to decode a char and get back the same char.
Following is my simple test.
I’m confused, If i have to encode or decode. Tried both. Both print the same result.
Any suggestions are greatly helpful.
char inpData = '†';
String str = Character.toString((char) inpData);
byte b[] = str.getBytes(Charset.forName("MacRoman"));
System.out.println(b[0]); // prints -96
String decData = Integer.toString(b[0]);
CharsetDecoder decoder = Charset.forName("MacRoman").newDecoder();
ByteBuffer inBuffer = ByteBuffer.wrap(decData.getBytes());
CharBuffer result = decoder.decode(inBuffer);
System.out.println(result.toString()); // prints -96, expecting to print †
CharsetEncoder encoder = Charset.forName("MacRoman").newEncoder();
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(decData));
result = decoder.decode(bbuf);
System.out.println(result.toString());// prints -96, expecting to print †
Thank you.
When you do
String decData = Integer.toString(b[0]);, you create the string “-96” and that is the string you’re encoding/decoding. Not the original char.You have to change your String back to a byte before.
To get your character back as a char from the -96 you have to do this :
With this your reversing your first transformation from
char->String->byte[0]by doingbyte[0]->String->char[0]If you have the String “-96”, you must change first your string into a byte with :