user3633965 user3633965 - 4 years ago 142
Java Question

java OutputStreamWriter and CP437

I am trying the following code, my problem is with the characters i put to get the byte array

the char É should correspond to 144 according to its charset set but i got the value of -55 when i ran the code,

if i used $ i will get 36 which is correct?

thanks for your help

try {
ByteArrayOutputStream result = new ByteArrayOutputStream();
Writer wr = new OutputStreamWriter(result, "CP437");
wr.write("É");//
wr.close();
ba2 = result.toByteArray();
result.close();

} catch (Exception x) {
x.printStackTrace();
}

Answer Source

CP437 encoding requires 8 bits to store, I executed your code and found the value stored in a byte as -112, É corresponding to 144 is outside the range of a standard byte (-127 to 128). convert it to an unsigned or positive value to obtain the correct result, use the following code to convert to an unsigned value:

public static int unsignedToBytes(byte b) {
    return b & 0xFF;
}

printing this value:

System.out.println(unsignedToBytes((byte) ba2[0]));

gives 144 which is your required value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download