Bitwise operators and bit manipulation (no solution?) - c++

I've been racking my brain trying to come up with a solution, but am stuck.
I have a function, this function takes the input (either 0b0, 0b1, or 0b10) and sets the bit of some variable - or at least it's supposed to.
The value it's changing has two states: either 0b100 or 0b101. I want to set the respective bit from the input. This is easy for the true bits, but tricky for the false bits. Some pseudo code for all the scenarios:
if (var == 0b100 && input == 0b0) { do nothing } // bit already set
if (var == 0b101 && input == 0b0) { var = 0b100 } // bit is different, so we set it.
if (var == 0b100 && input == 0b1) { var = 0b101 } // bit is different, so we set it.
if (var == 0b101 && input == 0b1) { do nothing } // bit is already set
if (var == 0b100 && input == 0b10) { var = 0b110 } // bit is never set, so set it
if (var == 0b101 && input == 0b10) { var = 0b110 } // bit is never set, so set it
I don't want to cheat and make a separate statement for every possibility, I'd like a function for this. Here's what I've sort of strung together, but it obviously doesn't work:
if ( var ^ input )
{
var ^= input;
}
The issue with this code is that 3rd bit (far left one) is always true.
Is this even possible?
EDIT:
Here is the same question, just posed a different way (which will result in different answers).
A function takes input for one bit. I want to take the left most bit and compare that bit and only that bit to another variable. e.g. input = 0b10 compared to 0b101's second bit, 0b00, since 0b10's left most bit is the second one.
On rare occasion, the unchanging bit may change :P (not from me though), so 0b001 or 0b000 may be it's value. For this reason, I cannot create a dynamic mask and compare only my bit.. The best method to solve my issue would be to answer this alternative question. Thanks a ton for your help, guys!

Step 1: Mask out the lower two bits.
var &= 0b100;
Step 2: Assign the lower two bits through OR operation.
var |= input;
Note that you may need to change the bit mask in step 1 in actual code base on the actual data type.

Related

Will if-else statements nest without brackets?

I want to write something utterly ridiculous that calls for a great depth of conditional nesting. The least disorienting way to write this is to forgo brackets entirely, but I have not been able to find any info on if nesting single-statement if-else guards is legal; the non-nested version causes people enough problems it seems.
Is it valid to write the following? (In both C and C++, please let me know if they differ on this.)
float x = max(abs(min), abs(max));
uint32 count = 0u;
// divides and conquers but, tries to shortcut toward more common values
if (x < 100'000.f)
if (x < 10.f)
count = 1u;
else
if(x < 1'000.f)
if (x < 100.f)
count = 2u;
else
count = 3u;
else
if (x < 10'000.f)
count = 4u;
else
count = 5u;
else
... // covers the IEEE-754 float32 range to ~1.0e+37 (maybe 37 end branches)
--skippable lore--
The underlying puzzle (this is for fun) is that I want to figure out the number of glyphs necessary to display a float's internal representation without rounding/truncation, in constant time. Counting the fractional part's glyph count in constant time was much neater/faster, but unfortunately I wasn't able to figure out any bit-twiddling tricks for the integer part, so I've decided to just brute-force it. Never use math when you can use your fists.
From cppreference.com:
in nested if-statements, the else is associated with the closest if that doesn't have an else
So as long as every if has an else, nesting without brackets works fine. The problem occurs when an else should not be associated with the closest if. For example:
if ( condition1 ) {
if ( condition2 )
DoSomething();
} // <-- This is needed so the else goes with the intended if.
else
DoOtherThing();
A quick scan of your code looks like it's fine.

How do bitwise operations work on expressions within variable assignments in C/C++?

I'm learning reverse engineering, and I have the following snippet which I am trying to make sense of:
var = strcmp("C:\\Windows\\System32\\svchost.exe", pe.szExeFile);
if (var)
var = -(var < 0) | 1;
if (var)
{
// additional code here
}
I think I understand most of what is going on here, but I'm confused about the purpose of the
var = -(var < 0) | 1; line. I'm only very vaguely familiar with C/C++, so I'm having a hard time wrapping my head around what this line does.
I understand that it's a bitwise OR, but I'm unsure how the -(var < 0) works. Is the expression inside the parentheses evaluated to a 1 or 0 and then the negative is applied and the OR? Is it evaluated as a boolean? If so, how does the | work on a boolean?
Or am I totally missing the point here?
strcmp() returns one of three possible results:
< 0
0
> 0
Assumed common two's complement, after the first if the variable var will be
-1 for the former "< 0"
0 for the former "= 0"
+1 for the former "> 0"
However, the second if will be taken only if var is non-zero.
The "mysterious" first if has no effect, as far as the source is concerned that you show.

Use non-const variable in place of required const variable (C++)

Part of a program I'm writing involves getting a list of integers (e.g. 15, 18, 25) and converting each one to binary. I'm iterating through the list and using the following line of code to convert each one:
std::string binary = std::bitset<8>(v).to_string();
(the (v) is the integer I'm converting)
but the problem with this line of code is that it defines the length of the outputted binary string, so 2 would become "00000010" and 31 would become "00011111" of course I cant it make too low or else im going to have some trouble with larger numbers, but I want the length of each binary string to be equal to the real binary number (2 is "10", 31 is "11111"). I have my reasons for this.So I tried replacing the <8> with an int that changes based on the number I'm trying to convert based on the following code:
int length_of_binary;
if (v <= 1) {
length_of_binary = 1;
}
else if (v <= 3) {
length_of_binary = 2;
}
else if (v <= 8) {
length_of_binary = 4;
}
else if (v <= 16) {
length_of_binary = 5;
}
else if (v <= 32) {
length_of_binary = 6;
}
std::string binary = std::bitset<length_of_binary>(v).to_string();
The problem is that i get the following error when hovering over the (now under-waved) variable length_of_binary:
"+5 overloads. expression must have a constant value."
and the program won't compile. I even tried tricking the compiler by assigning
the value of length_of_binary to a const int but it still won't work. Is there a way to fix this? if not is there a piece of code/function that will give me what I need?
As already mentioned in the comments: the issue you face is that the value needs to be known at compile time (not runtime dependent).
Hence, you can use a fixed representation, for example std::bitset<N> convert it into a string like you have already done and then trim the leading zeros.
It can be achieved like this:
std::string text = std::bitset<8>(25).to_string(); // binary representation
text.erase(0, text.find_first_not_of('0')); // zeroes trimmed
std::cout << text; // prints out: 11001
Note that this is just an example. You would still have to handle the case of 0 and think whether your input data won't exceed an 8 bit representation.
Nevertheless, with this approach you have no need for the length_of_binary variable and the related if-else sections - which simplifies the code a lot.

C++ multiple operators: assign A or B not equal to C

I am currently learning from an SDL2/OpenGL2 example code, for ImGui. Then, I ran into a line (and a few more alike) as shown below. I believe this part binds SDL mouse events to IMGUI API. However, I do not quite understand how it works.
io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0
where,
ImGuiIO& io = ImGui::GetIO();
bool mouseDown[5]; // a member of ImGuiIO struct
static bool g_MousePressed[3] = { false, false, false };
Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
(I hope above is enough information...)
What makes me the most confused is the the last part, not equal to 0. I could understand it, if it was a simple assignment of the result of an And and an Or operations. However, there is not equal to zero following at the end and I have not seen this before. I would like to get some help to understand this code please.
expression != 0
is a boolean expression and thus evaluates to either true or false which can be converted to integer values of 0 or 1.
#include <iostream>
int main() {
constexpr size_t SDL_BUTTON = 5;
for (size_t mouseMask = 0; mouseMask < 16; ++mouseMask) {
std::cout << mouseMask << ' '
<< (mouseMask & SDL_BUTTON) << ' '
<< ((mouseMask & SDL_BUTTON) != 0) << '\n';
}
}
Live demo: http://ideone.com/jcmosg
Since || is the logical or operator, we are performing a logical comparison that tests whether io.MouseDown != 0 or (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0 and yields a boolean value (true or false) promoted to whatever type io.mouseDown[0] is.
The code could actually have been written as:
io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT))
or
const bool wasPressed = g_mousePressed[0];
const bool newPress = mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT);
const either = (wasPressed == true) || (newPress == true);
io.MouseDown[0] = either;
or
if (g_mousePressed[0])
io.MouseDown[0] = 1;
else if (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT))
io.MouseDown[0] = 1;
else
io.MouseDown[0] = 0;
See http://ideone.com/TAadn2
If you are intending to learn, find yourself a good sandbox (an empty project file or an online ide like ideone.com etc) and teach yourself to experiment with pieces of code you don't immediately understand.
An expression a = b || c!=0 means a = (b!=0) || (c!=0). In boolean logic, b and b!=0 are equivalent. That's what I think the most confusing part. Once this is understood, there should be no problem.
Note that this expression should not be confused with a=b|c!=0, where | is a binary operation called "bit-wise or", as opposed to the logical operation ||, which is the logical "or". When doing b|c!=0, c!=0 is calculated first to yield a logical value 0 or 1, then b|0 or b|1 is calculated to do nothing (first case) or reset the last bit of the binary code of b to 1 (second case). Finally, that result is assigned to a. In this case, b and b!=0 are not equivalent, because the bit-wise or | is used instead of the logical or ||.
Similarly, & is the "bit-wise and" operator, while && is the logical "and". These two should not be confused either.
Notice that != has a higher precedence than ||, so the whole expression is indeed a simple assignment of the result of an OR.
The !=0 part is a way to turn the result of applying a bitmask into bool, as #AlekDepler said. Funny thing is its pretty much redundant (if mouseMask is of built-in integral type) as implicit conversion from say int to bool works exactly like !=0.

Understanding "Bitwise-And (&)" and "Unary complement(~)" in c++

I have some trouble understanding Bitwise-And and Unary Complement when both are used in this code snippet
if((oldByte==m_DLE) & (newByte==m_STX)) {
int data_index=0;
//This below line --- does it returns true if both the oldByte and newByte are not true
//and within timeout
while((timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))) {
if(Serial.available()>0) {
oldByte=newByte;
newByte=Serial.read();
if(newByte==m_DLE) {
.
.
.
are the both operators & ~are performing a logical not operation like checking until if both oldByte and newByte are false
The above code is from the link --> line 227 of the code
I am trying to use the implement the code for my application in C but without the timing functions
if((oldByte==DLE) && (newByte== STX)) {
data_index = 0;
// is this the correct implematation for above C++ code to C
while(! ((oldByte== DLE) && (newByte== ETX))){
oldByte = newByte;
Is this method correct for implementing in C
(timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))
is equivalent to (but probably less readable than)
(timeout.read_s()<m_timeout) && !(oldByte==m_DLE && newByte==m_ETX)
which is equivalent to (and IMO less readable than)
(timeout.read_s()<m_timeout) && (oldByte!=m_DLE || newByte!=m_ETX)
Edit: should add a caveat about short-circuiting. Although the particular example statements will all return the same value, using && or || will skip evaluating pieces that can't impact the result. This isn't important in your specific example, but could be very important in an example like this:
(oldByte!=nullptr & *oldByte == m_ETX) // will crash when oldByte=nullptr.
(oldByte!=nullptr && *oldByte == m_ETX) // will evaluate to false when oldByte=nullptr.
Since the equality-operator (==) yields 0 or 1 as a result, you can use bitwise and, too. (foo==1) & ~(bar==1) works too, since the AND with (foo==1), which always results in 1 and 0, masks all other bits in ~(bar==1). However, it is strongly recommended to use the logical counterparts &&, || and !.
The following would not work as expected:
if (~(bar == 1) & ~(foo == 1))
e.g. if foo = bar = 1, then it would evaluate to 0xfffffffe on ia32, which is different from 0 and therefore "TRUE"