无符号8位整数的左移运算 [英] Left shift operation on an unsigned 8 bit integer

查看:355
本文介绍了无符号8位整数的左移运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解C/C ++中的移位运算符,但是它们给了我一个艰难的时刻.

I am trying to understand shift operators in C/C++, but they are giving me a tough time.

我有一个无符号的8位整数,初始化为一个值,例如说1.

I have an unsigned 8-bit integer initialized to a value, for the example, say 1.

uint8_t x = 1;

据我所知,它在内存中的表示方式类似于 | 0 | 0 | 0 | 0 | 0 || 0 ||| 0 || 1 | .现在,当我尝试将变量x保留16位时,我希望获得输出 0 .但是令我惊讶的是,我得到了 65536 .我肯定会缺少一些我无法获得的东西.

From my understanding, it is represented in the memory like |0|0|0|0|0||0||0||1|. Now, when I am trying to left shit the variable x by 16 bit, I am hoping to get output 0. But to my surprise, I am getting 65536. I am certainly missing something which I am not able to get.

这是我的代码:

#include <iostream>

int main() {
    uint8_t x = 1;
    std::cout<<(x<<16)<<"\n";
    return 0;
}

这是一个幼稚的问题,但它困扰着我很多.

It's a naive question, but it is bothering me a lot.

推荐答案

在此表达式中

x<<16

整数提升适用于两个操作数.因此,表达式的结果是一个int类型的对象.

the integer promotions are applied to the both operands. So the result of the expression is an object of the type int.

尝试以下演示程序

#include <iostream>
#include <iomanip>
#include <type_traits>
#include <cstdint>


int main() 
{
    uint8_t x = 1;

    std::cout << std::boolalpha << std::is_same<int, decltype( x<<16 )>::value << '\b';

    return 0;
}

其输出是

true

根据C ++标准(8.8个Shift运算符)

From the C++ Standard (8.8 Shift operators)

  1. ...操作数应为整数或无范围的枚举类型,并且进行整体促销.结果的类型是提升后的左操作数.

这篇关于无符号8位整数的左移运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆