Programing

시프트 연산자는 Java에서 어떻게 작동합니까?

crosscheck 2020. 6. 24. 07:40
반응형

시프트 연산자는 Java에서 어떻게 작동합니까? [복제]


이 질문에는 이미 답변이 있습니다.

교대 연산자를 이해하려고 노력했지만 많은 것을 얻을 수 없었습니다. 아래 코드를 실행하려고 할 때

System.out.println(Integer.toBinaryString(2 << 11));
System.out.println(Integer.toBinaryString(2 << 22));
System.out.println(Integer.toBinaryString(2 << 33));
System.out.println(Integer.toBinaryString(2 << 44));
System.out.println(Integer.toBinaryString(2 << 55));

나는 아래를 얻는다.

1000000000000    
100000000000000000000000    
100    
10000000000000    
1000000000000000000000000    

누군가 설명해 주시겠습니까?


System.out.println(Integer.toBinaryString(2 << 11)); 

이진수 2 ( 10)를 왼쪽으로 11 번 이동합니다. 그 후:1000000000000

System.out.println(Integer.toBinaryString(2 << 22)); 

이진수 2 ( 10)를 왼쪽으로 22 번 이동합니다. 그 후 :100000000000000000000000

System.out.println(Integer.toBinaryString(2 << 33)); 

이제 int는 4 바이트이므로 32 비트입니다. 따라서 33만큼 이동하면 1만큼 이동하는 것과 같습니다.100


이진수 10 진수 시스템에서 2는 다음과 같습니다.

10

지금 당신이 할 경우

2 << 11

오른쪽에 11 개의 0이 채워집니다.

1000000000000

부호있는 왼쪽 시프트 연산자 "<<"는 비트 패턴을 왼쪽으로 이동하고 부호있는 오른쪽 시프트 연산자 ">>"는 비트 패턴을 오른쪽으로 이동합니다. 비트 패턴은 왼쪽 피연산자에 의해 제공되며 오른쪽 피연산자에 의해 이동할 위치 수입니다. 부호없는 오른쪽 시프트 연산자 ">>>"는 0을 가장 왼쪽 위치로 이동하고 ">>"뒤의 가장 왼쪽 위치는 부호 확장 [..] 에 따라 다릅니다 .

왼쪽 쉬프팅은 항 또는 산술에서 2 (* 2)의 곱셈 결과


예를 들어

바이너리에서 2 10이면 그렇게 <<1할 것 100입니다.4

바이너리로 4 100이면 그렇게 <<1할 것 1000입니다.8


참조


오른쪽 및 왼쪽 이동은 오른쪽 이동의 작동 방식과 동일하게 작동합니다. 오른쪽 이동 : 오른쪽 이동 연산자 >>는 값의 모든 비트를 지정된 횟수만큼 오른쪽으로 이동합니다. 일반적인 형태 :

value >> num

여기에서 num은 값을 오른쪽으로 이동하는 위치 수를 지정합니다. 즉, >>는 지정된 값의 모든 비트를 num으로 지정된 비트 위치 수만큼 오른쪽으로 이동합니다. 다음 코드 조각은 값 32를 오른쪽으로 두 위치 이동하여 결과를 8로 설정합니다.

int a = 32;
a = a >> 2; // a now contains 8

값에 "시프트 오프"된 비트가 있으면 해당 비트가 손실됩니다. 예를 들어, 다음 코드 프래그먼트는 값 35를 오른쪽 두 위치로 이동시켜 두 하위 비트가 손실되도록하여 다시 8로 설정됩니다.

int a = 35;
a = a >> 2; // a still contains 8

바이너리에서 동일한 연산을 보면 이것이 어떻게 일어나는지 더 명확하게 보여줍니다

00100011 35 >> 2
00001000 8

값을 오른쪽으로 이동할 때마다 해당 값을 2로 나누고 나머지는 버립니다. 이것을 고성능 정수 나누기 2로 활용할 수 있습니다. 물론 오른쪽 끝에서 비트를 이동하지 않아야합니다. 오른쪽으로 이동하면 오른쪽 이동으로 노출 된 맨 위 (가장 왼쪽) 비트가 맨 위 비트의 이전 내용으로 채워집니다. 이를 부호 확장이라고하며 음수를 올바르게 이동하면 부호가 유지됩니다. 예를 들어, –8 >> 1is는 –42 진수로

11111000 –8 >>1
11111100 –4

It is interesting to note that if you shift –1 right, the result always remains –1, since sign extension keeps bringing in more ones in the high-order bits. Sometimes it is not desirable to sign-extend values when you are shifting them to the right. For example, the following program converts a byte value to its hexadecimal string representation. Notice that the shifted value is masked by ANDing it with 0x0f to discard any sign-extended bits so that the value can be used as an index into the array of hexadecimal characters.

// Masking sign extension.
class HexByte {
  static public void main(String args[]) {
    char hex[] = {
      '0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
  byte b = (byte) 0xf1;
 System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}

Here is the output of this program:

b = 0xf1

I believe this might Help:

    System.out.println(Integer.toBinaryString(2 << 0));
    System.out.println(Integer.toBinaryString(2 << 1));
    System.out.println(Integer.toBinaryString(2 << 2));
    System.out.println(Integer.toBinaryString(2 << 3));
    System.out.println(Integer.toBinaryString(2 << 4));
    System.out.println(Integer.toBinaryString(2 << 5));

Result

    10
    100
    1000
    10000
    100000
    1000000

Edited:

Must Read This (how-do-the-bitwise-shift-operators-work)


I think it would be the following, for example:

  • Signed left shift

[ 2 << 1 ] is => [10 (binary of 2) add 1 zero at the end of the binary string] Hence 10 will be 100 which becomes 4.

Signed left shift uses multiplication... So this could also be calculated as 2 * (2^1) = 4. Another example [2 << 11] = 2 *(2^11) = 4096

  • Signed right shift

[ 4 >> 1 ] is => [100 (binary of 4) remove 1 zero at the end of the binary string] Hence 100 will be 10 which becomes 2.

Signed right shift uses division... So this could also be calculated as 4 / (2^1) = 2 Another example [4096 >> 11] = 4096 / (2^11) = 2


It will shift the bits by padding that many 0's.

For ex,

  • binary 10 which is digit 2 left shift by 2 is 1000 which is digit 8
  • binary 10 which is digit 2 left shift by 3 is 10000 which is digit 16

The shift can be implement with data types (char, int and long int). The float and double data connot be shifted.

value= value >> steps  // Right shift, signed data.
value= value << steps  // Left shift, signed data.

Signed left shift Logically Simple if 1<<11 it will tends to 2048 and 2<<11 will give 4096

In java programming int a = 2 << 11;

// it will result in 4096

2<<11 = 2*(2^11) = 4096

The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.

For example,

i >>= 2

produces the same result as

i = i >> 2

참고URL : https://stackoverflow.com/questions/10910913/how-do-shift-operators-work-in-java

반응형