ucloudu
V2EX  ›  2018

c 语言里面关于左移

  •  
  •   ucloudu · Apr 12, 2018 · 2313 views
    This topic created in 2981 days ago, the information mentioned may be changed or developed.

    #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 replies    2018-04-12 19:43:52 +08:00
    wsy2220
        1
    wsy2220  
       Apr 12, 2018
    %x 会把你的参数强制转换成 unsigned int
    ucloudu
        2
    ucloudu  
    OP
       Apr 12, 2018
    @wsy2220 我直接 sizeof(bb << 16) 你猜是多少,结果是 4
    fgodt
        3
    fgodt  
       Apr 12, 2018
    你自己都找出来问题了 bb << 16 被转换成 int 了
    XiaoxiaoPu
        4
    XiaoxiaoPu  
       Apr 12, 2018
    (unsigned) char/short int 在参与运算前会先转换为 (unsigned) int
    ucloudu
        5
    ucloudu  
    OP
       Apr 12, 2018
    @XiaoxiaoPu 谢谢谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   987 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:05 · PVG 03:05 · LAX 12:05 · JFK 15:05
    ♥ Do have faith in what you're doing.