简体   繁体   English

在C ++中比较uint8_t和uint16_t

[英]Compare uint8_t and uint16_t in c++

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. 我想知道如何测试用户是否在uint8中键入两个或更多字节。 And tell him to retype the value of just one byte.that's why i tried to compare uint8_t to uint16_t. 并告诉他只键入一个字节的值。这就是为什么我尝试将uint8_t与uint16_t进行比较。

The problem with the above code is that you are testing for a negative value in an unsigned integer . 上面的代码的问题在于,您正在测试unsigned integernegative The if(y < 0) part will always be false. if(y < 0)部分将始终为false。

Now, from my understanding you want to filter values that are greater than 1Byte . 现在,据我所知,您希望过滤大于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] . 您知道,对于给定的byte您具有2^8 - 1 8-1的值范围,即,无符号数位于[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 . 这样,您的问题就可以简化为简单的检查,也就是说, if the input value is greater than 255, throw away that input (Ofc you have to check for < 0 values) (Ofc您必须检查< 0值)

There are other solutions to this but without any context I can't provide a precise answer. 还有其他解决方案,但是没有任何上下文,我无法提供准确的答案。 Hope the above simplification helps. 希望以上简化对您有所帮助。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM