developer tip

실제 프로젝트에서 비트 시프 팅을 사용해야했던 적이 있습니까?

optionbox 2020. 10. 9. 11:06
반응형

실제 프로젝트에서 비트 시프 팅을 사용해야했던 적이 있습니까?


실제 프로그래밍 프로젝트에서 비트 시프 팅 을 사용해야했던 적이 있습니까? 대부분의 (모두는 아니지만) 고급 언어에는 시프트 연산자가 있지만 실제로 언제 사용해야합니까?


나는 여전히 하드웨어에서 부동 소수점을 지원하지 않는 시스템에 대한 코드를 작성합니다. 이러한 시스템에서는 거의 모든 산술에 대해 비트 시프 팅이 필요합니다.

또한 해시를 생성하려면 시프트가 필요합니다. 다항식 산술 (CRC, Reed-Solomon 코드는 주류 응용 프로그램 임) 또는 시프트도 사용합니다.

그러나 시프트는 편리하고 작가가 의도 한 바를 정확하게 표현하기 때문에 사용됩니다. 원하는 경우 곱셈을 사용하여 모든 비트 시프트를 에뮬레이션 할 수 있지만 작성하기가 더 어렵고 가독성이 떨어지고 때로는 느립니다.

컴파일러는 곱셈을 시프트로 줄일 수있는 경우를 감지합니다.


네, 많이 사용했습니다. 비트 트위들 링은 비트 마스크가 매우 일반적인 임베디드 하드웨어에서 중요합니다. 모든 마지막 성능이 필요할 때 게임 프로그래밍에서도 중요합니다.

편집 : 또한 색상 심도 변경 또는 RGB <-> BGR 변환과 같이 비트 맵을 조작하는 데 많이 사용합니다.


  • 열거 형에 대한 멋진 플래그 값 만들기 (수동으로 1, 2, 4를 입력하는 대신 ...)
  • 비트 필드에서 데이터 압축 풀기 (많은 네트워크 프로토콜에서 사용)
  • Z- 커브 횡단
  • 성능 해킹

그리고 나는 그들이 사용되는 많은 경우를 생각할 수 없습니다. 일반적으로 다른 방법입니다. 특정 문제가 있으며 비트 연산을 사용하면 최상의 결과를 얻을 수 있습니다 (보통 성능-시간 및 / 또는 공간 측면에서).


내가 항상 사용하는 한 곳은 크로스 플랫폼 애플리케이션을 위해 정수의 엔디안을 전치 할 때입니다. 또한 2D 그래픽을 블리 팅 할 때 (다른 비트 조작 연산자와 함께) 유용합니다.


나는 그것들을 몇 번 사용했지만 거의 항상 바이너리 파일 형식을 구문 분석하는 데 사용되었습니다.


합리적인 기사 : http://greatjustice.info/the-lost-art-of-bitmasks/


비트 시프트가 빠릅니다. 분할 및 모듈러스 연산이 수행되기 훨씬 전에 CPU 명령 세트에서 구현되었습니다. 우리 중 많은 사람들이 연필과 종이로는 간단하지만 CPU에서는 사용할 수없는 산술에 비트 시프트를 사용했습니다.

예를 들면 :

  • 나는 큰 합성물을 소인수로 분해하는 것과 관련된 프로젝트에 비트 시프트를 사용했습니다.
  • 또한 임의로 큰 정수의 제곱근과 세제곱근을 찾기 위해 비트 시프트를 사용했습니다.

예, 여전히 필요합니다.

예를 들어 여기서는 직렬 포트 COMx를 통해 PLC와 통신하기위한 소프트웨어를 개발합니다. 한 바이트 내에서 비트를 처리 할 필요가 있으며 왼쪽 / 오른쪽 시프트 및 논리 연산자 OR, XOR, AND를 매일 사용합니다.

예를 들어, 바이트의 비트 3 (오른쪽에서 왼쪽)을 켜야한다고 가정 해 보겠습니다.

다음을 수행하는 것이 훨씬 더 효율적입니다.

Byte B;

B := B XOR 4;

대신에:

Byte B = 0;
String s;  // 0 based index

s = ConvertToBinary (B);
s[5] = "1";
B := ConvertToDecimal (s);

문안 인사.


어셈블리 언어로 작성했을 때 내 코드는 비트 시프 팅과 마스킹으로 가득 차있었습니다.

C에서도 상당한 양을 보냈습니다.

자바 스크립트 나 서버 언어로는 많이하지 않았습니다.

아마도 가장 현대적인 용도는 1과 0으로 표시된 부울 값의 패킹 된 배열을 단계별로 살펴 보는 것입니다. 나는 항상 왼쪽으로 시프트하고 어셈블리에서 부호 비트를 확인했지만 더 높은 수준의 언어에서는 값과 비교합니다.

예를 들어, 8 비트가있는 경우 "if (a> 127) {...}"로 최상위 비트를 확인합니다. 그런 다음 왼쪽 시프트 (또는 2로 곱하기)를 수행하고 127로 "and"를 수행 한 다음 (또는 마지막 비트가 설정된 경우 256을 빼고) 다시 수행합니다.


비트 맵의 ​​비트가 압축 된 이미지 압축 / 압축 해제에 많이 사용했습니다. http://en.wikipedia.org/wiki/Huffman_coding을 사용하면 압축되는 항목은 다양한 비트 수 (모두 바이트 정렬되지 않음)로 구성되므로 인코딩 또는 디코딩 할 때 비트 시프트가 필요합니다. .


예를 들어 C, C ++와 같은 언어의 암호화 방법 구현에서. 바이너리 파일, 압축 알고리즘 및 논리 목록 연산-비트 연산은 항상 좋습니다 =)


비트 시프 팅은 높은 수준의 프로그래밍 문제를 해결하지 못하지만 우리는 때때로 낮은 수준의 문제를 해결해야하며이를 수행하기 위해 C로 별도의 라이브러리를 작성할 필요가없는 것이 편리합니다. 그것이 가장 많이 사용되는 때입니다.

저는 개인적으로 EBCDIC 문자 집합 변환기 용 인코더를 작성하는 데 사용했습니다 .


네, 있어요. 의심 할 수 있듯이, 장치 드라이버 개발과 같은 저수준 프로그래밍에서 발견 될 가능성이 가장 높습니다. 하지만 의료 기기에서 데이터를 수신하는 웹 서비스를 개발해야하는 C # 프로젝트에서 작업했습니다. 장치가 저장 한 모든 이진 데이터는 SOAP 패킷으로 인코딩되었지만 이진 데이터는 압축 및 인코딩되었습니다. 따라서 압축을 풀려면 많은 비트 조작을해야합니다. 또한 유용한 정보를 분석하기 위해 많은 비트 이동을 수행해야합니다. 예를 들어 장치 일련 번호는 두 번째 바이트의 아래쪽 절반 또는 이와 비슷한 것입니다. 또한 .NET (C #) 세계의 일부 사람들이 비트 마스킹 및 플래그 특성을 사용하는 것을 보았습니다. 개인적으로 그렇게하고 싶은 충동이 없었습니다.


네. 나는 이전에 암호화 알고리즘을 작성해야하는데 확실히 사용합니다.

They are also useful when using integers etc for keeping track of statuses.


When converting numbers from little endian to the big endian format and vice versa


I work for a computer peripheral manufacturer. I've encountered, and had to implement code that uses bit shifts, pretty much every day.


Fast Fourier transform — FFT and it's Cooley-Tukey technique will require use bit shifting operations.


Find the nearest power of two greater or equal to given number:

1 << (int)(ceil(log2(given)))

Needed for texturing on hardware that does not support arbitrary texture sizes.


Bit shifting is used a lot in deciphering the protocols of online games. The protocols are designed to use a little bandwidth as possible, so instead of transmitting the number of players on a server, names and so forth in int32s, all the information is packed into as few bytes as possible. It's not really necessary these days with most people using broadband, but when they were originally designed people used 56k modems for gaming, so every bit counted.

The most prominent examples of this are in Valve's multiplayer games particularly Counter-Strike, Counter-Strike Source. The Quake3 protocol is also the same, however Unreal isn't quite as slimline.

Here's an example (.NET 1.1)

string data = Encoding.Default.GetString(receive);

if ( data != "" )
{
    // If first byte is 254 then we have multiple packets
    if ( (byte) data[0] == 254 )
    {
        // High order contains count, low order index
        packetCount = ((byte) data[8]) & 15; // indexed from 0
        packetIndex = ((byte) data[8]) >> 4;
        packetCount -= 1;

        packets[packetIndex] = data.Remove(0,9);
    }
    else
    {
        packets[0] = data;

    }
}

Of course whether you view this as a real project or just a hobby (in C#) is up to you.


Yes, used them in MPEG2-2 Transport stream parser. It was easier and was better readable.


I had to write a program to parse the .ifo files on DVD discs. These are the fileds that explain how many titles, chapters, menus, etc. are on the disc. They are made up of packed bits of all sizes and alignments. I suspect many binary formats require similar bit shifting.


I have seen bitwise operators used when multiple flags were used as a property parameter. For example number 4 = 1 0 0 means that one of the three flags is set. This is not good for public API but it can speed up things in special cases since checking for bits is fast.


Every bitblt-er i ever wrote couldn't have been completed w/o ability to slide bits left and right.


I've used them on games for packing a bunch of flags into a single byte / char for saving out to a data card. Things like storing the status of unlockables etc. Not so much of a requirement nowadays, but can save work.


I use it in a project for an embedded system that has to read a monitor's EDID data. Some data in an EDID is encoded like this:

Byte #3:
Horizontal Blanking -- lower 8 bits
Byte #4:
Lower Nibble: Horizontal Blanking -- upper 4 bits
Upper Nibble: something else

Yes, when performing binary communication between Java and C# applications, one is big-endian byte ordering and the other is little-endian (not necessarily on this order). I created an InputStream class that could read numbers with a different byte order, and it used byte-shifting in order to work.

Sometimes also when you want to put 4 shorts in the 4 bytes of a long, it would be case the of using byte shifting. I think I did that many years ago...


Another very common thing is to do a 4 bit shift when extracting the high nibble of a byte, i.e.

#define HIGH_NIBBLE(byte) (((byte) >> 4) & 0x0F)
#define LOW_NIBBLE(byte)  ( (byte)       & 0x0F)

Bit shifting is also required when communicating with "lower level" equiment, eq digital ethernet-IO -boxes or PLC's, which usually pack invidual input/output values into bytes.


Yes, bit shifting is being used at low-level embedded software all the time. It can also be used as an almost magic trick to perform extremely fast math operations, have a look at

http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/


Yes, all the time. Like these macros for packing and unpacking a 3space coordinate to/from a 32-bit integer:

#define Top_Code(a, b, c)           ((((a) + x) << 20) | (((b) + y) << 10) | ((c) + z))                           
#define From_Top_Code(a, b, c, f)   (a = (((f) >>> 20) - x), b = ((((f) & 0xffc00) >>> 10) - y), c = (((f) & 0x3ff) - z))        

참고URL : https://stackoverflow.com/questions/520625/have-you-ever-had-to-use-bit-shifting-in-real-projects

반응형