【问题标题】:Compare uint8_t and uint16_t in c++比较 c++ 中的 uint8_t 和 uint16_t
【发布时间】:2018-06-06 12:51:02
【问题描述】:

我想测试输入变量的值是否通过了一个字节大小或知道所以我写了这段代码

{
    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;
}

我想知道如何测试用户是否在 uint8 中输入了两个或更多字节。 并告诉他重新输入一个字节的值。这就是我尝试将 uint8_t 与 uint16_t 进行比较的原因。

【问题讨论】:

标签: c++ compare uint8t uint16


【解决方案1】:

上述代码的问题在于您正在测试unsigned integer 中的negative 值。 if(y &lt; 0) 部分将始终为假。

现在,据我了解,您希望过滤大于 1Byte 的值。你知道,对于给定的byte,你有2^8 - 1 的值范围,也就是说,无符号数位于[0-255] 的范围内。因此,您的问题被简化为一个简单的检查,即if the input value is greater than 255, throw away that input。 (你必须检查 &lt; 0 值)

对此还有其他解决方案,但没有任何上下文,我无法提供准确的答案。希望以上简化对您有所帮助。

【讨论】:

  • 是的,我明白了,但我想强制用户为给定的变量类型输入正确的字节数。
【解决方案2】:

为了检查一个值是否在一个小类型的范围内,你必须先将它分配给一个更大的类型。您根本无法对小类型本身进行检查,因为它永远不会包含您想要检查的太大值。

uint16_t tempX;
uint8_t x;
cin >> hex >> tempX;
if (tempX > 0xff)
    cout << "error";
else
    x = (uint8_t)tempX;

【讨论】:

  • 当我输入 tempX 0xfffff..uint16_t 无法支持它。
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多