manbearpig1 manbearpig1 - 2 months ago 26
Java Question

Narrowing conversion from byte to char Java

I read that although type byte occupies 8 bits of memory, and type char occupies 16 bits of memory, the conversion from byte to char is considered narrowing because byte is signed, while char is unsigned. I think this means that when we convert a type byte with a negative value to char, we lose the negative and so that is our loss of information and so the conversion is narrowing.

I am trying to test this in a Java program.

public class Test
{
public static void main (String[] args)
{
byte num = -1;
char test = (char)num;
System.out.println(test);
}
}


I expected that printing test would output:

1


This would be -1 without the negative sign because char is unsigned. This in fact outputs:

?


Is there something wrong with my program or with my idea about converting byte to char?

Answer

That's not how signs or char works.

  1. Bear in mind that System.out.println will show you the UTF-8 character (which is the same as ascii for the first 8 bits of values) for a char. So System.out.println((char)71); will print "G". So when you expect to see "1" to be printed, what you're saying is that you expect (char)-1 == 41. If you want the numeric value, you should cast it to int before printing.
  2. System.out.println will substitute a question mark for unprintable characters.
  3. byte to char first is converted to an int. The doc (linked by Sotirios Delimanolis) says;

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).

Where

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T