Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "int mask = ~0;"?

I saw the following line of code here in C.

 int mask = ~0;

I have printed the value of mask in C and C++. It always prints -1.

So I do have some questions:

  • Why assigning value ~0 to the mask variable?
  • What is the purpose of ~0?
  • Can we use -1 instead of ~0?
like image 658
Jayesh Avatar asked Sep 23 '17 06:09

Jayesh


People also ask

What are binary masks used for?

Bit masks are used to access specific bits in a byte of data. This is often useful as a method of iteration, for example when sending a byte of data serially out a single pin.

What is masking in code?

In computer science, a mask or bitmask is data that is used for bitwise operations, particularly in a bit field. Using a mask, multiple bits in a byte, nibble, word, etc. can be set either on or off, or inverted from on to off (or vice versa) in a single bitwise operation.

How do you mask the least significant bit?

The usual way is to take a 1 , and shift it left n bits. That will give you something like: 00100000 . Then subtract one from that, which will clear the bit that's set, and set all the less significant bits, so in this case we'd get: 00011111 . A mask is normally used with bitwise operations, especially and .


2 Answers

It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.

like image 147
Richard Hodges Avatar answered Oct 23 '22 18:10

Richard Hodges


C and C++ allow 3 different signed integer formats: sign-magnitude, one's complement and two's complement

~0 will produce all-one bits regardless of the sign format the system uses. So it's more portable than -1

You can add the U suffix (i.e. -1U) to generate an all-one bit pattern portably1. However ~0 indicates the intention clearer: invert all the bits in the value 0 whereas -1 will show that a value of minus one is needed, not its binary representation

1 because unsigned operations are always reduced modulo the number that is one greater than the largest value that can be represented by the resulting type

like image 36
phuclv Avatar answered Oct 23 '22 17:10

phuclv