zoukankan      html  css  js  c++  java
  • csapp 2.2.5 Signed versus Unsigned in C

    2.2.5 Signed versus Unsigned in C

    • C supports both signed and unsigned arithmetic for all of its integer data types.
    • most numbers are signed by default.
    • Adding charchter 'U' or 'u' as a suffix creates an unsigned constant
    • C allows conversion between unsigned and signed
      • most systems follow the rule that the underlying bit representation does not change(这里意思是底层的表示不变,那么怎么表示就是看是有符号还是没有符号)
      • unsigned ( ightarrow) signed (U2T_w)
      • signed ( ightarrow) unsigned (T2U_w)
        (w is the number of bits for the data type)

    Conversions can happen due to explicit(显式) casting:

    int tx, ty;
    unsigned ux, uy;
    
    tx = (int) ux;
    uy = (unsigned) ty;
    

    happen implicitly:

    int tx, ty;
    unsigned ux, uy;
    
    tx = ux; /* Cast to signed */
    uy = ty; /* Cast to unsigned */
    

    print a value of type int with directive %u and a value of type unsigned with directive %d:

    int x = –1;
    //0x8000 0000
    unsigned u = 2147483648; /* 2 to the 31st */
    
    printf(“x = %u = %d
    ”, x, x);
    printf(“u = %u = %d
    ”, u, u);
    
    //answer
    x = 4294967295 = –1
    u = 2147483648 = –2147483648
    

    -8的补码1000
    signed + unsigned ( ightarrow) unsigned + unsigned (implicity)
    example:

    #include<bits/stdc++.h>
    using namespace std;
    int main ()
    {
        printf("%d",(-1<0U));
        return 0;
    }
    

    Consider the comparison –1 < 0U,the second operand is unsigned.the first one is implicitly cast to unsigned. so the expression is equivalent to the comparison 4294967295U < 0U

  • 相关阅读:
    vue 开发系列 企业微信整合
    MongoDB基础3
    MongoDB基础2
    MongoDB基础1
    SpringBoot MongoDB
    UWSGI
    Nginx
    编译python源码
    Flask部署
    Django个人工作总结
  • 原文地址:https://www.cnblogs.com/strategist-614/p/14418237.html
Copyright © 2011-2022 走看看