0

i would like to test if a value of an input variable passed one byte size or know so i write this code

{
    uint8_t x;
    cout << " enter x" << endl;
    cin  >> hex >> x;
    cout << hex << x;
    uint8_t y ;  
    y = x >> 4 ;
    cout << hex << y;
    if ( y == 0 )
    {
        cout << " succes, coorect value for x";
    }
    if (y >  0)
    {
        /*here i supoosed that x = 0xfff and when shifting, y would be 0xff but y is uint8 so it's just for compare
        std::cout << "fail, ";
    }
    return 0;
}

I would like to know how to test if the user type two or more byte in uint8. And tell him to retype the value of just one byte.that's why i tried to compare uint8_t to uint16_t.

gerrard2461
  • 305
  • 1
  • 6
  • 21
  • 2
    Given that `y` is an unsigned value, can you [explain to your rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) how could `y` possibly be ever less than 0? – Sam Varshavchik Jun 06 '18 at 12:54
  • 2
    `if ( y < 0 )` this will never be true. `y` is an unsigned integer. – Borgleader Jun 06 '18 at 12:55
  • 1
    Possible duplicate: [Detect Integer Overflow in Input](https://stackoverflow.com/questions/12938053/detect-integer-overflow-in-input) – NathanOliver Jun 06 '18 at 12:58
  • [GCC warns](https://godbolt.org/g/TCuznK) about this by the way. – chris Jun 06 '18 at 13:01
  • 1
    One problem is that `uint8_t` might be `unsigned char` and `istream` has an [`operator>>`](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2) that reads this as a character and not as a number. – Bo Persson Jun 06 '18 at 13:05
  • Sorry for compare y to zero in fact i would like to compare to zero i would like if y ==0 – gerrard2461 Jun 07 '18 at 07:46

2 Answers2

0

The problem with the above code is that you are testing for a negative value in an unsigned integer. The if(y < 0) part will always be false.

Now, from my understanding you want to filter values that are greater than 1Byte. You know, that for a given byte you have 2^8 - 1 range of values, that is, the unsigned number lies in the range [0-255]. Thus, your problem is reduced to a simple check, that is, if the input value is greater than 255, throw away that input. (Ofc you have to check for < 0 values)

There are other solutions to this but without any context I can't provide a precise answer. Hope the above simplification helps.

KostasRim
  • 2,053
  • 1
  • 16
  • 32
  • yeah , i see that but i would like to oblige the user to enter a correct number of byte to a given variable type. – gerrard2461 Jun 07 '18 at 07:53
0

In order to check if a value is in the range of a small type, you have to assign it to a bigger type first. You simply cannot do the check with the small type itself because it can never contain that too huge value you want to check for.

uint16_t tempX;
uint8_t x;
cin >> hex >> tempX;
if (tempX > 0xff)
    cout << "error";
else
    x = (uint8_t)tempX;
sebrockm
  • 5,733
  • 2
  • 16
  • 39