I am pretty much new to C++ and especially signed and unsigned conversions. Currently I am doing one exercise, where I need to compare a value if it is between a two values (one minimum and maximum).
For example
minimum value = -319 - it's byte array (of int8) will be {254, 193}
maximum value = 400 - it's byte array (of int8) {1, 144}
Assume the value to be compared between is -200 {255, 56}, which should be valid, but I am not able to get it correctly.
Assume the compare value, minimum and maximum value bytes is ANDed with 255 unsigned mask byte, which is then stored in int8 byte and then compared between min and max value. Due to the sign bit I am confused and not able to correctly get the comparison, but for all positive values is working fine.
The methods I tried were,
First I tried to convert int8_t to int16_t
int16_t compare = (int16_t)(inp[i] & 0xFF);
int16_t minVal = (int16_t)(minimum[i] & 0xFF);
int16_t maxVal = (int16_t)(maximum[i] & 0xFF); return (compare>=minVal&&compare<=maxVal)
Second method was I set 0 to MS bit in mask byte and then comparing each byte, since I thought comparison with that bit is not needed, but I am not sure if it is right as the data might get wrong.
Third try was to set 0 the MS Bit while comparing . I tried it and this is also a failure.
Please let me know how to compare in this scenario. Thank you
So to clarify the question I get a three 2-element byte arrays, and the function will return true, if the value byte array is inbetween min and max byte array.
So the comparison algorithm above is ran in a for loop:
bool isValueInBetween(uint8_t* min, uint8_t* max, uint8_t* val){
bool is_match = true;
for(int i = 0; i < 2; i++){
int8_t compare = (inp[i] & 0xFF); //masking is used just because in the book it was mentioned, in case different mask occurs, but I think in this case it is not needed
int8_t minVal = (minimum[i] & 0xFF);
int8_t maxVal = (maximum[i] & 0xFF);
if (!(compare>=minVal&&compare<=maxVal))
is_match = false;
}
return is_match;
}
The above algorithm works for positive values, but doesn't work in negative or mixed value scenarios(say min in negative and max in positive). Please let me know any good books for C++.