This discussion is archived
2 Replies Latest reply: Aug 24, 2007 8:20 AM by 807605 RSS

Byte to Char ...

807605 Newbie
Currently Being Moderated
Hi,

I have written an encryption function in PHP which at a certain point uses the built in chr() function to convert a byte back to a character. This works fine, however when I do the same thing in Java ( by casting the byte as a char ) I have problems.

It seems characters with ASCCI values greater than 128 are being displayed as the wrong characters and sometimes not at all ( they become ? ).

Some example output from the PHP ...

_____Byte______ASCCI_______Char

....-785314906..........166...................... �
....805139163...........219.......................�

Im assuming this is because the way PHP handles the bytes differs from java. Does anyone know how I can get my java representation of these bytes to work for conversion to characters ?

My java code goes like this ...
System.out.println((char)(byte) byteCode)
* byteCode is an integer variable containing values like those shown above.

Many thanks for any insight ...

Chris
  • 1. Re: Byte to Char ...
    807605 Newbie
    Currently Being Moderated
    A byte is only 8 bits and it's signed as well so 1 bit is reserved for the sign.
    As a consequence a byte in Java has the numerical range of -128 to 127.

    Just for the record, as far as I know a byte could never have the values -785314906 or 805139163 in any language unless that language defines a byte to be something other than a byte.

    Try the following to convert your "byteCode"s:
    System.out.println((char)(0xff & byteCode));
  • 2. Re: Byte to Char ...
    807605 Newbie
    Currently Being Moderated
    Nice one, thanks a load thats fixed it !!!