Hello!

We ask this question more for self-education than from a real momentary need:

**What do you need to know the programmers “higher levels” about batch operations? What specific cases are it desirable to know in any case? Give examples from your practice when the use of beaten operations has significantly accelerated / simplified? / Improved your code? **

**What I already know: **

- I know about Bit masks .
- I know that “X & AMP; 1” checks the readiness of the number (for example, here, answer @avp )
- I know about Bitched shifts and multiplication / division to degree degree.

Also, I read all the topics on this topic here on the hashkode and the main on Stackoverflow, found this interesting resource: Bit Twiddling Hacks .

Also I have a heard about An amazing solution for finding Fast Inverse Square Root .

and heard about the book Hacker’s Delight , which has not yet read. It is in Russian .

In addition to the question I will write that besides bit masks (which I have been using it for a long time) from all that I met, the only more or less useful for myself and its *everyday practice *I found only Checking the number of attention, which caused me to think that certainly there should be any other cases where the use of bit operations is appropriate and even preferably.

And I also write that I am interested in this question of a purely from the practical side, therefore rather I will be grateful for simple examples and real experience than for dry references to “6 Tom of the World Assembly of Algorithms from any Great British educational institution” and everything in so hard.

Thank you))

**List of interesting links to adjacent topics **

Obtaining a module of the number without comparison operation

Do BitWise Operators (Other Than SHIFTS) Make Any Mathematical Sense in Base-10?

## Answer 1, Authority 100%

Bit operations are usually needed only for extreme optimization. In normal cases, you can do without them. In normal cases, bit tricks make it difficult to understand the code, apply them only if they are consciously needed. Please note that modern compilers are pretty smart, and the bit tricks apply themselves. Many programmers, unfortunately, abuse low-level optimizations, which harms the quality of the code: the code becomes very difficult in support, fragile, and subject to thin errors.

On the other hand, once the bit operations are so often used, it is worth knowing them to be able to correctly read and understand someone else’s code.

To work with packaged values in C (and C++), for example, it is usually not better to use shifts and masks, but Bit fields . The compiler itself takes care of the desired shift values. In C (and it seems in C++ ) To highlight the older and younger semipitis, it is better to use such a structure:

```
typeedef union lh
{
Char C;
struct {char h: 4; Char L: 4; };
} LH;
```

(Note, the standard does not guarantee the correctness of this, since, for example, there is no guarantee that byte contains *exactly *8 bits).

An important private case in which bit operations are needed – an array of bit (for example, you want to use *a lot of *Boolean values, and want to sacrifice the speed of winning in the size of the data structure. For this you can get a big Array `Char `

OV, and add bits in it as follows:

```
// 8 bits per byte = & gt; We divide on 8 to get the number of Bit
Inline Char & Amp; Carrier (int n) {Return Payload [N & GT; & GT; 3]; }
// Select a bit in Bath: The mask of three younger bits is 0B111 = ((1 & lt; & lt; 3) - 1)
// 1 & lt; & lt; X gives a number with one crown bit
INLINE INT BIT (INT N)
{
Const int threeBitMask = (1 & lt; & lt; 3) - 1);
int bitnumber = N & amp; ThreeBitMask;
Return 1 & lt; & lt; Bitnumber;
}
INLINE BOOL GETBIT (INT N)
{
RETURN CARRIER (N) & AMP; Bit (n);
}
INLINE VOID SETBIT (INT N, BOOL VALUE)
{
If (Value)
Carrier (N) | = Bit (N);
ELSE.
Carrier (n) & amp; = ~ bit (n);
}
```

(not 100% sure in the correctness of the code). On the other hand, it has already been done once for us, in C++ there is `std :: BITSET `

, to invent the bike is not worth it.

Another important particular case is the implementation of algorithms like cryptographic, which themselves operate with the bit representations of numbers. Here, of course, without bit arithmetic make sure.

## Answer 2, Authority 125%

Most (for me, naturally), the bit operation is `XOR `

– *excluding or *. The operation `XOR `

is remarkable in that the use of 2 times to the same bit array restores its initial values that is its property actively applied in encryption operations:

```
c = a xor b // coding with the vector b
A = c xor b // restore the original value
```

More details here

The second most important (again for me) operation `and `

is often used for “travel” from a long bit sequence of a particular part. Well, for example, there is a `long `

, which should be split into two `INT `

‘A. Another example: There is a long bit sequence that say, returns some filament stotty controller at least a stupid device, the manual says that the 3rd bit shows the availability of the device. We take a bite mask where in the 3rd position of the unit (4), and everything else is 0, we put on the bit array and check & GT; 0:

```
if ((Bitsfromcontroller & amp; 4) & gt; 0)
// Ready!
```

Well, you already wrote everything yourself about the bitsticks, so I will not repeat.

and `or `

it’s just the addition of two bitmasters.

**Update **

Table Bits Conversion byte in 16-tiric string (Java):

```
/ * In essence, it is necessary to divide the input bytes to two 4-bit elements * /
Public String BYTETOHEX (BYTE B) {// Suppose 76 = 01001100
Final String Hex = "0123456789Abcdef";
Char [] Val = New Char [2];
Val [0] = Hex.Charat (B & GT; & gt; & gt; 4); // Kill 4 younger bits get 4 = 0100
VAL [1] = Hex.Charat (B & AMP; 15); // We assign a mask (15 = 00001111) for 4 younger bits we get 12 = 1100
Return String.Valueof (VAL); // Return 4C = 76
}
```

## Answer 3, Authority 62%

And no one still has not remembered flags and enumerations?

For example, we want to write to a variable some many days of the week (here and hereinafter – C #)

```
enum weekdaymask
{
None = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64.
}
```

Now all the weekend can be written as:

```
var holidays = weekdaymask.saturday | Weekdaymask.sunday;
```

Check that day – day off

```
var isholiday = day & amp; Holidays! = weekdaymask.none;
```

## Answer 4, Authority 38%

When you have to convert pictures between formats with different color depths, bit operations help handle several pixels at a time. Suppose it is necessary to convert 4 4-bit values to 4 8-bit: 0xabcd – & gt; 0xa0b0c0d0. This can be done somehow so (and possibly quickly):

```
v2 = ((V & LT; & lt; 8) | v) & amp; 0x00FF00FF; // 0xab00cd.
v = ((v2 & lt; & lt; 4) | v2) & amp; 0x0F0F0F0F;
```

4 bytes is not very much, but on MMX / SSE, all the same, but registers 64-128-bit.

with similar tricks I, for example, made the creation of radiance around objects (on the usual two-dimensional raster). Although the most difficult in the event was to choose how much pixels should be blocked into one cell. As a result, I chose the average option (4 in one int’e) and made the preliminary calculation of all possible masks for all 16 pixel options in Int’e (each source pixel I either created a radiance or not).