Programing

비트 연산자 란 무엇입니까?

crosscheck 2020. 7. 7. 07:46
반응형

비트 연산자 란 무엇입니까?


나는 재미를 위해 코드를 작성하고 학문적 또는 전문적인 환경에서 실제로 코드를 탐구하지 않은 사람이므로 이러한 비트 연산자와 같은 것들이 실제로 나를 피합니다.

비트 단위 연산을 지원하는 JavaScript에 대한 기사를 읽었습니다. 나는이 작업이 장소에서 언급 된 것을 계속 보았고 정확히 무엇인지 알아 내려고 노력했지만 전혀 이해하지 못하는 것 같습니다. 그래서 그들은 무엇입니까? 명확한 예가 좋을 것입니다! :디

몇 가지 질문이 더 있습니다. 비트 단위 연산의 실제 응용 프로그램은 무엇입니까? 언제 사용할 수 있습니까?


아무도 왜 이것이 유용한 지에 대한 주제를 밝히지 않았습니다.

플래그로 작업 할 때 비트 연산을 많이 사용합니다. 예를 들어, 일련의 플래그를 작업에 전달하려는 경우 (예 : File.Open()읽기 모드와 쓰기 모드가 모두 활성화 된 경우) 단일 값으로 전달할 수 있습니다. 이는 가능한 각 플래그를 비트 세트 (바이트, short, int 또는 long)로 자체 비트를 할당하여 수행됩니다. 예를 들면 다음과 같습니다.

 Read: 00000001
Write: 00000010

따라서 읽기 및 쓰기를 전달하려면 (READ | WRITE)를 전달한 다음 둘을 결합합니다.

00000011

그런 다음 다른 쪽 끝에서 해독 할 수 있습니다.

if ((flag & Read) != 0) { //...

어떤 검사

00000011 &
00000001

어떤 반환

00000001

0이 아니므로 플래그는 READ를 지정합니다.

XOR을 사용하여 다양한 비트를 토글 할 수 있습니다. 플래그를 사용하여 방향 입력 (위, 아래, 왼쪽, 오른쪽)을 지정할 때 이것을 사용했습니다. 예를 들어 스프라이트가 가로로 움직이고 있고 돌아 서고 싶은 경우 :

     Up: 00000001
   Down: 00000010
   Left: 00000100
  Right: 00001000
Current: 00000100

이 경우에는 LEFT를 끄고 오른쪽으로 켜는 (LEFT | RIGHT)로 현재 값을 XOR합니다.

비트 이동은 여러 경우에 유용합니다.

x << y

와 같다

x * 2

2의 거듭 제곱을 빠르게 곱해야하지만 1 비트를 최상위 비트로 이동하는 것을 조심해야한다면 부호가없는 한 숫자를 음수로 만듭니다. 다른 크기의 데이터를 처리 할 때도 유용합니다. 예를 들어, 4 바이트에서 정수를 읽는 경우 :

int val = (A << 24) | (B << 16) | (C << 8) | D;

A가 가장 중요한 바이트이고 D가 가장 작은 것으로 가정합니다. 결과는 다음과 같습니다.

A = 01000000
B = 00000101
C = 00101011
D = 11100011
val = 01000000 00000101 00101011 11100011

색상은 종종 이런 식으로 저장됩니다 (가장 중요한 바이트는 무시되거나 알파로 사용됨).

A = 255 = 11111111
R = 21 = 00010101
G = 255 = 11111111
B = 0 = 00000000
Color = 11111111 00010101 11111111 00000000

값을 다시 찾으려면 맨 아래에 올 때까지 비트를 오른쪽으로 이동 한 다음 나머지 상위 비트를 마스킹하십시오.

Int Alpha = Color >> 24
Int Red = Color >> 16 & 0xFF
Int Green = Color >> 8 & 0xFF
Int Blue = Color & 0xFF

0xFF와 동일합니다 11111111. 본질적으로 Red의 경우 다음을 수행합니다.

Color >> 16 = (filled in 00000000 00000000)11111111 00010101  (removed 11111111 00000000)
00000000 00000000 11111111 00010101 &
00000000 00000000 00000000 11111111 =
00000000 00000000 00000000 00010101 (The original value)

다른 답변으로 나열된 단일 비트 진리표는 한 번에 하나 또는 두 개의 입력 비트에서만 작동한다는 점에 주목할 가치가 있습니다. 다음과 같은 정수를 사용하면 어떻게됩니까?

int x = 5 & 6;

답은 각 입력의 이진 확장에 있습니다.

  5 = 0 0 0 0 0 1 0 1
& 6 = 0 0 0 0 0 1 1 0
---------------------
      0 0 0 0 0 1 0 0

각 열의 각 비트 쌍은 "AND"기능을 통해 실행되어 맨 아래 줄에 해당 출력 비트를 제공합니다. 따라서 위의 표현에 대한 답은 4입니다. CPU는이 열에서 8 개의 개별 "AND"연산을 각 열마다 하나씩 병렬로 수행했습니다.

나는 아직도이 "AHA!"가 있다는 것을 기억하기 때문에 이것을 언급한다. 몇 년 전에 내가 알게 된 순간.


비트 연산자는 한 번에 조금씩 작동하는 연산자입니다.

AND는 두 입력이 모두 1 인 경우에만 1입니다.

하나 이상의 입력이 1이면 OR은 1입니다.

XOR is 1 only if exactly one of its inputs are 1.

NOT is 1 only if its input are 0.

These can be best described as truth tables. Inputs possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the two inputs.

AND|0 1      OR|0 1
---+----    ---+----
  0|0 0       0|0 1
  1|0 1       1|1 1

XOR|0 1     NOT|0 1
---+----    ---+---
  0|0 1        |1 0
  1|1 0

One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:

    203: 1100 1011
AND  15: 0000 1111
------------------
 IS  11: 0000 1011

These are the bitwise operators, all supported in JavaScript:

  • op1 & op2 -- The AND operator compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.

  • op1 | op2 -- The OR operator compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.

  • op1 ^ op2 -- The EXCLUSIVE-OR operator compares two bits and returns 1 if either of the bits are 1 and it gives 0 if both bits are 0 or 1.

  • ~op1 -- The COMPLEMENT operator is used to invert all of the bits of the operand.

  • op1 << op2 -- The SHIFT LEFT operator moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.

  • op1 >> op2 -- The SHIFT RIGHT operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is preserved.

  • op1 >>> op2 -- The SHIFT RIGHT - ZERO FILL operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is discarded.


To break it down a bit more, it has a lot to do with the binary representation of the value in question.

For example (in decimal):
x = 8
y = 1

would come out to (in binary):
x = 1000
y = 0001

From there, you can do computational operations such as 'and' or 'or'; in this case:
x | y = 
1000 
0001 |
------
1001

or...9 in decimal

Hope this helps.


When the term "bitwise" is mentioned, it is sometimes clarifying that is is not a "logical" operator.

For example in JavaScript, bitwise operators treat their operands as a sequence of 32 bits (zeros and ones); meanwhile, logical operators are typically used with Boolean (logical) values but can work with non-Boolean types.

Take expr1 && expr2 for example.

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

a = "Cat" && "Dog"     // t && t returns Dog
a = 2 && 4     // t && t returns 4

As others have noted, 2 & 4 is a bitwise AND, so it will return 0.

You can copy the following to test.html or something and test:

<html>
<body>
<script>
    alert("\"Cat\" && \"Dog\" = " + ("Cat" && "Dog") + "\n"
        + "2 && 4 = " + (2 && 4) + "\n"
        + "2 & 4 = " + (2 & 4));
</script>

In digital computer programming , a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits . It is a fast, primitive action directly supported by the processor , and is used to manipulate values for comparisons and calculations.

operations:

  • bitwise AND

  • bitwise OR

  • bitwise NOT

  • bitwise XOR

  • etc

List item

    AND|0 1        OR|0 1 
    ---+----      ---+---- 
      0|0 0         0|0 1 
      1|0 1         1|1 1 

   XOR|0 1        NOT|0 1 
   ---+----       ---+--- 
     0|0 1           |1 0 
     1|1 0

Eg.

    203: 1100 1011
AND  15: 0000 1111
------------------
  =  11: 0000 1011

Uses of bitwise operator

  • The left-shift and right-shift operators are equivalent to multiplication and division by x * 2y respectively.

Eg.

int main()
{
     int x = 19;
     printf ("x << 1 = %d\n" , x <<1);
     printf ("x >> 1 = %d\n", x >>1);
     return 0;
}
// Output: 38 9
  • The & operator can be used to quickly check if a number is odd or even

Eg.

int main()
{
    int x = 19;
    (x & 1)? printf("Odd"): printf("Even");
    return 0;
 }
// Output: Odd
  • Quick find minimum of x and y without if else statment

Eg.

int min(int x, int y)
{
    return y ^ ((x ^ y) & - (x < y))
}
  • Decimal to binary conversion

Eg.

#include <stdio.h>
int main ()
{
    int n , c , k ;
    printf("Enter an integer in decimal number system\n " ) ;
    scanf( "%d" , & n );
    printf("%d in binary number
    system is: \n " , n ) ;
    for ( c = 31; c >= 0 ; c -- )
    {
         k = n >> c ;
         if ( k & 1 )
              printf("1" ) ;
         else
              printf("0" ) ;
      }
      printf(" \n " );
      return 0 ;
}
  • The XOR gate encryption is popular technique, becouse of its complixblity and reare use by the programmer.
    • bitwise XOR operator is the most useful operator from technical interview perspective.

bitwise shifting works only with +ve number

Also there is a wide range of use of bitwise logic


It might help to think of it this way. This is how AND (&) works:

It basically says are both of these numbers ones, so if you have two numbers 5 and 3 they will be converted into binary and the computer will think

         5: 00000101
         3: 00000011

are both one: 00000001 0 is false, 1 is true

So the AND of 5 and 3 is one. The OR (|) operator does the same thing except only one of the numbers must be one to output 1, not both.


I kept hearing about how slow JavaScript bitwise operators were. I did some tests for my latest blog post and found out they were 40% to 80% faster than the arithmetic alternative in several tests. Perhaps they used to be slow. In modern browsers, I love them.

I have one case in my code that will be faster and easier to read because of this. I'll keep my eyes open for more.

참고URL : https://stackoverflow.com/questions/276706/what-are-bitwise-operators

반응형