V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ucloudu
V2EX  ›  2018

c 语言里面关于左移

  •  
  •   ucloudu · 2018-04-12 18:25:35 +08:00 · 1486 次点击
    这是一个创建于 2177 天前的主题,其中的信息可能已经有所发展或是发生改变。

    #include <stdio.h>
    int main() {
    // 64 位系统
    unsigned short bb = 1024;
    printf("%d\n", sizeof(bb));
    printf("%0x\n", bb); printf("%0x\n", (bb << 16));
    }
    很简单的一个 c 语言的程序,运行环境为: Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 9.0.0 (clang-900.0.39.2) Target: x86_64-apple-darwin17.4.0
    结果是: 2 400 4000000 我记得当时学组成原理的时候,左移高位是舍弃的,这面为什么结果和预想的不一样呢,是不是编译器优化呢?还是这面的 bb << 16 只是一个临时的值,这个临时值的不是 unsigned short 的,那这个临时值的类型一般是啥呢?

    5 条回复    2018-04-12 19:43:52 +08:00
    wsy2220
        1
    wsy2220  
       2018-04-12 18:30:29 +08:00
    %x 会把你的参数强制转换成 unsigned int
    ucloudu
        2
    ucloudu  
    OP
       2018-04-12 18:32:16 +08:00
    @wsy2220 我直接 sizeof(bb << 16) 你猜是多少,结果是 4
    fgodt
        3
    fgodt  
       2018-04-12 18:35:18 +08:00
    你自己都找出来问题了 bb << 16 被转换成 int 了
    XiaoxiaoPu
        4
    XiaoxiaoPu  
       2018-04-12 19:20:49 +08:00
    (unsigned) char/short int 在参与运算前会先转换为 (unsigned) int
    ucloudu
        5
    ucloudu  
    OP
       2018-04-12 19:43:52 +08:00
    @XiaoxiaoPu 谢谢谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   988 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 20:15 · PVG 04:15 · LAX 13:15 · JFK 16:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.