470,849 Members | 1,071 Online

# converting from bit->byte->char->byte

Hi! I have the problem where I cast a bit string of "10000000" to a
byte, which i get -128; this is fine so far. However, when I take this byte
and cast it to a char, I get a question mark('?'). So when i go to cast it
back to a byte, i now get 63 (the ascii representation of a question mark).
I see that for any byte from 128 to 256 i'll get a question mark... must be
java's way of indicating that's it's negative or something.... my
question to you all is:

1) Why is it doing this?

2) What can I do so that I can cast -128 to char and back to a byte to
get -128 again?

Thanks!
Jul 17 '05 #1
2 69104
Hi,

As I understand it, A byte goes from -128 to 128. A char goes from 0 to 255.
So, to convert from byte to a char correctly, you could do this:

byte b = -128;
char c = (char)b;
System.out.println(c);
char c2 = (char)(b + 128);
System.out.println(c2);
byte b2 = (byte)(c2 -128);

Clunky, but works.
Depends on what you want to use it for, you may want to try using a reader
or a stream..

Steve

"Nicholas Parnell" <ni**************@cse-cst.gc.ca> wrote in message
news:10*************@news.drenet.dnd.ca...
Hi! I have the problem where I cast a bit string of "10000000" to a
byte, which i get -128; this is fine so far. However, when I take this byte and cast it to a char, I get a question mark('?'). So when i go to cast it back to a byte, i now get 63 (the ascii representation of a question mark). I see that for any byte from 128 to 256 i'll get a question mark... must be java's way of indicating that's it's negative or something.... my
question to you all is:

1) Why is it doing this?

2) What can I do so that I can cast -128 to char and back to a byte to
get -128 again?

Thanks!

Jul 17 '05 #2
A better way to make a char from a byte would be:

byte b = -128;
//To Char
char c = (char)(b & 0xFF);
//To Byte
byte b2 = (byte)(c & 0xFF);

"Nicholas Parnell" <ni**************@cse-cst.gc.ca> wrote in message
news:10*************@news.drenet.dnd.ca...
Hi! I have the problem where I cast a bit string of "10000000" to a
byte, which i get -128; this is fine so far. However, when I take this byte and cast it to a char, I get a question mark('?'). So when i go to cast it back to a byte, i now get 63 (the ascii representation of a question mark). I see that for any byte from 128 to 256 i'll get a question mark... must be java's way of indicating that's it's negative or something.... my
question to you all is:

1) Why is it doing this?

2) What can I do so that I can cast -128 to char and back to a byte to
get -128 again?

Thanks!

Jul 17 '05 #3

### This discussion thread is closed

Replies have been disabled for this discussion.