Операторы побитового сдвига вправо в Java
В C / C ++ есть только один оператор сдвига вправо '>>', который следует использовать только для положительных целых чисел или целых чисел без знака. Использование оператора сдвига вправо для отрицательных чисел не рекомендуется в C / C ++, а при использовании для отрицательных чисел вывод зависит от компилятора (см. Это). В отличие от C ++, Java поддерживает следующие два оператора сдвига вправо.
1) >> (Signed right shift) In Java, the operator ‘>>’ is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator ‘>>’ uses the sign bit (left most bit) to fill the trailing positions after shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if binary representation of number is 10….100, then right shifting it by 2 using >> will make it 11…….1.
See following Java programs as example ‘>>’
class Test { public static void main(String args[]) { int x = - 4 ; System.out.println(x>> 1 ); int y = 4 ; System.out.println(y>> 1 ); } } |
Выход:
-2 2
2) >>> (Unsigned right shift) In Java, the operator ‘>>>’ is unsigned right shift operator. It always fills 0 irrespective of the sign of the number.
class Test { public static void main(String args[]) { // x is stored using 32 bit 2"s complement form. // Binary representation of -1 is all 1s (111..1) int x = - 1 ; System.out.println(x>>> 29 ); // The value of "x>>>29" is 00...0111 System.out.println(x>>> 30 ); // The value of "x>>>30" is 00...0011 System.out.println(x>>> 31 ); // The value of "x>>>31" is 00...0001 } } |
Выход:
7 3 1
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.