14 Mayıs 2020 Perşembe

Shift Operators

Giriş
Shit Operators
1. Signed shift (yani >>) ve
2. Unsigned Shift (>>>) olarak ayrılırlar.

1. Signed Shit ve Unsigned Shift Arasındaki Fark Ne Zamandır Var
Bu fark assembly dilinde var ve ilk olarak 1955 yılında ortaya çıkmış. Açıklaması şöyle
The assembly language for many processors use the phrase "arithmetic shift" to represent the bitwise shift of a signed value, and "logical shift" for an unsigned value. The two types of shift are the same when shifting leftward, filling the least-significant bits with 0. However, a rightward logical (unsigned) shift fills the most-significant bits with 0, whereas a rightward arithmetic (signed) shift fills the upper bits with a copy of the old sign bit (MSB).
2. Signed Shift - Arithmetic Shift
Açıklaması şöyle
>>> will always put a 0 in the left most bit, while >> will put a 1 or a 0 depending on what the sign of it is.
Örnek
Şöyle yaparız
System.out.println(Integer.toBinaryString(-1));
// prints "11111111111111111111111111111111"
System.out.println(Integer.toBinaryString(-1 >> 16)); //eksi sayı olduğu için 1 ekler
// prints "11111111111111111111111111111111"
System.out.println(Integer.toBinaryString(-1 >>> 16));//Hep 0 ekler. O da gösterilmez
// prints "1111111111111111"
3. Unsigned Shift - Logical Shift
Sayının soluna hep 0 ekler.

Örnek
1 olan bitlerin konumunu bulmak için şöyle yaparız. Sola hep 0 eklendiği için num değişkeni 0'dan farklı olduğu sürece kontrolü yapılabilir.
List<Integer> bits(int num) {
  List<Integer> setBits = new ArrayList<>();
  for (int i = 0; num != 0; ++i, num >>>= 1) {
    if ((num & 1) != 0) setBits.add(i);
  }
  return setBits;
}

Hiç yorum yok:

Yorum Gönder