views:

40

answers:

2

Hi all, 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.

A: 
String decData = Integer.toString(b[0]);

This probably gets you the "-96" output in the last two examples. try

String decData = new String(b, "MacRoman");

Apart from that, keep in mind that System.out.println uses your system-charset to print out strings anyway. For a better test, consider writing your Strings to a file using your specific charset with something like

FileOutputStream fos = new FileOutputStream("test.txt"); 
OutputStreamWriter writer = new OutputStreamWriter(fos, "MacRoman");
writer.write(result.toString());
writer.close();
deadsven
Thank you for your prompt reply deadsven. Only new String(b, "MacRoman"); worked. File writing also created -96. :( . But, Is there a way i can get symbol † from integer -96 ?
metalhawk
A: 

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 :

    String string = new String(b, "MacRoman");
    char specialChar = string.charAt(0);

With this your reversing your first transformation from char -> String -> byte[0] by doing byte[0] -> String -> char[0]


If you have the String "-96", you must change first your string into a byte with :

byte b = Byte.parseByte("-96");
Colin Hebert
Thank you Colin for the clarification. So, I need to encode the string "-96" in "MacRoman" to get the symbol "†". In which i'm facing issues.I tried String str = new String(decData.getBytes(),"MacRoman"); Did not work as well.
metalhawk
In the test code, for example i have created the "b". But my problem is i just have the string "-96" out of which i need to get the char "†". I tried : new String("-96".getBytes(), "MacRoman"); Did not work :(
metalhawk
See the update.
Colin Hebert
Thank you very much Colin. That was a slick answer :)
metalhawk