I have tried to make a longer function but it has acted very weird. I had tried to isolate the problem and I have been able to find the buggy part.
This program made for an Arduino but this phenomenon probably appear in other environment. I have tried to make a lot of searches but I cannot find the solution.
So, my buggy part:
Why do not these two codes give the same result?
How can I construct a one line function without extra variable
but same operation like “Code 1”?
Results:
- Code 1: 0b00101100
- Code 2: 0b01101100
Source codes:
Code 1: (correct operation but not one line)
#include <binary.h>
const byte value=B00110110;
byte buffer,result;
void setup(){
Serial.begin(115200);
buffer = (value << 3);
result = (buffer >> 2);
Serial.println(result,BIN);
}
void loop(){
}
It gives: 0b00101100
Code 2: (incorrect operation but one line)
#include <binary.h>
const byte value=B00110110;
byte result;
void setup(){
Serial.begin(115200);
result = ((value << 3) >> 2);
Serial.println(result,BIN);
}
void loop(){
}
It gives: 0b01101100
I assume that your
byteis some unsigned integral type smaller thanint.Most arithmetic operations in C++ are performed in the domain of
inttype, after all “smaller” operands are implicitly converted (promoted) to typeint.For this reason, your first group of shifts is equivalent to
while your second group if shifts is equivalent to
In the first variant, any bits that get shifted outside the range of type
byteby the<< 3shift are lost during intermediate conversion and assignment tobuffer. In the second variant all calculations are performed within the range ofint, so nothing is lost.If you want your second variant to produce the same results as the first, you need to explicitly “truncate” the intermediate shift result