In Java, why does type casting of a character to an integer NOT extend the sign bit

StackOverflow https://stackoverflow.com/questions/8165264

  •  03-03-2021
  •  | 
  •  

سؤال

In Java a bitwise operation causes type casting to integer and also causes sign extension. For instance the following is expected:

byte b = -1;
System.out.println(b >> 1);//-1

In Java chars are encoded in UTF-16 and each unit is represented with 2 bytes.

char c = 0xFFFF; //I assume now the sign bit is 1.
System.out.println(c >> 1);//32767 ???? WHY

I was expecting -1 instead of 32767. Why is the sign not extended during the type cast before the bitwise operation is applied? Any ideas?

هل كانت مفيدة؟

المحلول

Because char is unsigned - 0xFFFF really has a value of 65535

نصائح أخرى

It works like that because of widening primitive conversion that is performed on shift arguments. Namely there's no information loss, including the sign of the type being converted.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top