What is masking? (Bitwise operators) [duplicate] - bit-manipulation

This question already has answers here:
What is bit masking?
(2 answers)
Closed 5 years ago.
I ran across an online explanation of what masking is with respect to bitwise operators, but was unable to fully understand the explanation due to the use of symbols that I'm not familiar with. Here is the demonstration:
The specific line that confuses me is "// Actual shift is 10 & (8-1) = 2
". I get that 10 is the number of bits that we want to shift left by, but what does "&" mean in this context, and why do we subtract 8-1?
Link to the demonstration can be found here:
https://msdn.microsoft.com/en-us/library/8xftzc7e(v=vs.100).aspx
Thanks in advance.

The answer is in the second paragraph of your own links remark section
The << operator masks expression2 to avoid shifting expression1 by too
much. Otherwise, if the shift amount exceeded the number of bits in
the data type of expression1, all the original bits would be shifted
away to give a trivial result. To ensure that each shift leaves at
least one of the original bits, the shift operators use the following
formula to calculate the actual shift amount: mask expression2 (using
the bitwise AND operator) with one less than the number of bits in
expression1.
Number of bits in a byte is 8. So the bitmask is 7, or 0b111. Apply this to 10 (0x1010) you arrive at 0x10 aka 2. That’s your shift amount.

Related

How can I turn the number 0-8 into the 0-8th binary position in C++?

I am trying to use the integers 1-8 to represent the binary positions D0-D7.
I'm at a loss at how to transform this. I tried taking the most significant bit, but that doesn't really work for this situation..
Any thoughts or pointers to resources on this topic? It's for addressing in an OLED screen.
I'm trying to think of a clever solution in C++. I could just make a switch table, but I thought there must be a cooler way to do it with bit manipulation!
For example
int x = 7
y = convert(x)
if (y == 0b01000000)
print("Success!!")
Thank you for any and all help!!
What you're looking for is bit shift - move all the bits in you variable either to left or right.
C++, among other languages uses << operator to shift bits to the left. You might find other bitwise operators useful for Your application.
Using this you can replace convert(x) with simply 1 << (x-1). That changes integers 1 to 8 (inclusive) to 0th to 7th bit position (inclusive).

What exactly is a bit vector in C++? [duplicate]

This question already has answers here:
C/C++ Bit Array or Bit Vector
(5 answers)
Closed 7 years ago.
So, I was reading a question in Cracking the Coding Interview: 5th Edition where it says to implement a bit vector with 4 billion bits. And it defines a bit vector as an array that compactly stores boolean values by using an array of ints. Each int stores a sequence of 32 bits, or boolean values. I am sort of confused in the above definition. Can someone explain me what exactly does the above statement mean?
The marked question that has been attached as duplicate, I couldn't really understand since their is no associated example. The second answer does have an example but it's not really understandable. It will be great if any of you can add an example, albeit for a small value only. Thanks!
The bool type is at least 1 byte. It means it's at least 8 bits.
In a 'int' type, on a 32bits system, it's 32 bits.
You then have 32 booleans in 4 bytes with int, instead of 32 bytes minimum if you use bool type.
In an int you can store 32 booleans by basic bit operations : &, | and ~

What does >> mean in C++ code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
That statement is filled with all sorts of magic. What exactly is it doing?
What does >> mean in C++ code?
For integer types, it's the binary right-shift operator, which takes the binary representation of its first operand, and moves it a number of places to the right. a >> b is roughly the same as a / pow(2,b).
That statement is filled with all sorts of magic. What exactly is it doing?
uint256 isn't a standard type or function; I'll assume it's a big-number type with 256 bits, with suitable operator overloads so that it acts like a standard numeric type. So uint256(0) is a 256-bit number with value zero.
~ is the binary negation operator; it zeros all set bits, and sets all zero bits. So ~uint256(0) will contain 256 bits, all set.
Finally, the shift moves those bits 32 bits to the right. So the top 32 bits will all be zero, and the remaining 224 bits will be set.
Assuming uint256 is a 256 bit unsigned integer type and the operators are defined as for the built-in types, this will:
initialize a 256 bit unsigned integer with 0
bitwise invert it (operator ~)
right-shift it by 32 bits (operator >>)
See Wikipedia on C / C++ operators
My guess is a shift. It's shifting the bits to the right, possibly by 32 bits. We can't say for sure without seeing the uint256 class due to c++ operator overloading.

What is >>> operation in C++

In this blog post the author has suggested the following as the bug fix:
int mid = (low + high) >>> 1;
Does anyone know what is this >>> operator? Certainly its not there on the following operator reference list:
http://msdn.microsoft.com/en-us/library/x04xhy0h%28v=vs.71%29.aspx
http://www.cplusplus.com/doc/tutorial/operators/
What is it and how does that solve the overflow problem?
>>> is not a part of C++. The blog contains code in Java.
Check out Java online tutorial here on Bitwise shift operators. It says
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
>>> is the logical right shift operator in Java.
It shifts in a zero on the left rather than preserving the sign bit. The author of the blog post even provides a C++ implementation:
mid = ((unsigned int)low + (unsigned int)high)) >> 1;
... if you right-shift unsigned numbers, preserving the sign bit doesn't make any sense (since there is no sign bit) so the compiler obviously uses logical shifts rather than arithmetic ones.
The above code exploits the MSB (32rd bit assuming 32 bit integers): adding low and high which are both nonnegative integers and fit thus into 31 bits never overflows the full 32 bits, but it extends to the MSB. By shifting it to the right, the 32 bit number is effectively divided by two and the 32rd bit is cleared again, so the result is positive.
The truth is that the >>> operator in Java is just a workaround for the fact that the language does not provide unsigned data types.
The >>> operator is in a Java code snippet, and it is the unsigned right shift operator. It differs from the >> operator in its treatment of signed values: the >> operator applies sign extension during the shift, while the >>> operator just inserts a zero in the bit positions "emptied" by the shift.
Sadly, in C++ there's no such thing as sign-preserving and unsigned right shift, we have only the >> operator, whose behavior on negative signed values is implementation-defined. To emulate a behavior like the one of >>> you have to perform some casts to unsigned int before applying the shift (as shown in the code snippet immediately following the one you posted).
The Java expression x >>> y is more or less equivalent to the C++ expression unsigned(x) >> y.
>>> is not C++ operator. I think it's an operator in Java language. I'm not sure though!
EDIT:
Yes. That is java operator. Check out the link to the article you provided. The article is using Java language!
It is a java operator, not related to C++.
However all the blog author does is change the division by 2 with a bit-wise right shift (i.e. right shifting the value by 1 is similar to dividing by 2 ^ 1).
Same functionality, different machine code output (bit shifting operations are almost always faster than multiplication/division on most architectures).

How can I set all bits to '1' in a binary number of an unknown size?

I'm trying to write a function in assembly (but lets assume language agnostic for the question).
How can I use bitwise operators to set all bits of a passed in number to 1?
I know that I can use the bitwise "or" with a mask with the bits I wish to set, but I don't know how to construct a mask based off some a binary number of N size.
~(x & 0)
x & 0 will always result in 0, and ~ will flip all the bits to 1s.
Set it to 0, then flip all the bits to 1 with a bitwise-NOT.
You're going to find that in assembly language you have to know the size of a "passed in number". And in assembly language it really matters which machine the assembly language is for.
Given that information, you might be asking either
How do I set an integer register to all 1 bits?
or
How do I fill a region in memory with all 1 bits?
To fill a register with all 1 bits, on most machines the efficient way takes two instructions:
Clear the register, using either a special-purpose clear instruction, or load immediate 0, or xor the register with itself.
Take the bitwise complement of the register.
Filling memory with 1 bits then requires 1 or more store instructions...
You'll find a lot more bit-twiddling tips and tricks in Hank Warren's wonderful book Hacker's Delight.
Set it to -1. This is usually represented by all bits being 1.
Set x to 1
While x < number
x = x * 2
Answer = number or x - 1.
The code assumes your input is called "number". It should work fine for positive values. Note for negative values which are twos complement the operation attempt makes no sense as the high bit will always be one.
Use T(~T(0)).
Where T is the typename (if we are talking about C++.)
This prevents the unwanted promotion to int if the type is smaller than int.