为什么我必须将一个字节转换为无符号两次以查看十六进制输出?

时间:2015-12-11 19:53:27

标签: c++ casting

我想将变量打印为十六进制:

    private void MakeNode(){
    for (int A = 1; A <= 42; A++){
    if(A==1){
        X=40;
        Y=40;
    }else if(A>1 && A<=7){
        X = X + 120;
        Y = 40;
    }else if(A==8){
        X = 40;
        Y = 160;
    }else if(A>8&& A<=14){
        X = X + 120;
        Y = 160;
    }else if(A==15){
        X = 40;
        Y = 280;
    }else if(A>15&& A<=21){
        X = X + 120;
        Y = 280;
    }else if(A==22){
        X = 40;
        Y = 400;
    }else if(A>22&& A<=28){
        X = X + 120;
        Y = 400;
    }else if(A==29){
        X = 40;
        Y = 520;
    }else if(A>29&& A<=35){
        X = X + 120;
        Y = 520;
    }else if(A==36){
        X = 40;
        Y = 640;
    }else if(A>36&& A<=42){
        X = X + 120;
        Y = 640;
    }
        cirA = new Circle(X,Y,16);
        //fxid = cir.concat(String.valueOf(A));
        //fxid = cir+String.valueOf(A);
        //cirA.setId(fxid);
        cirA.setFill(Color.YELLOW);
        cirA.setStroke(Color.BLACK);
        cirA.setStrokeWidth(4.0);
        pane.getChildren().add(cirA);

    }
}

输出似乎是:

#include <iostream>
#include <string>
#include <cstdint>

int main() {
    auto c = 0xb7;

    std::cout << std::hex << static_cast<unsigned char>(c) << std::endl;
    std::cout << std::hex << static_cast<unsigned>(static_cast<unsigned char>(c)) << std::endl;

    std::cout << std::hex << (uint8_t)(c) << std::endl;
    std::cout << std::hex << (unsigned)(uint8_t)(c) << std::endl;

    return 0;
}

我确实知道c设置了更高的位(\ufffd (tries to print it as a char) b7 \ufffd (tries to print it as a char) b7 ),但我已经将其转换为10110111uint8_t

为什么我必须再次将unsigned charuint8_t投射到unsigned char以获得预期的输出?

1 个答案:

答案 0 :(得分:1)

std::hexbasefield of the stream str 设置为hex,就好像通过调用str.setf(std::ios_base::hex, std::ios_base::basefield)一样。

  

当设置此基本域hex位时,iostream使用十六进制基数表示整数 I / O.

代码

#include <iostream>

int main()
{
    int i = 0xb7;
    unsigned u = 0xb7;
    char c = static_cast<char>(0xb7);
    unsigned char b = 0xb7;

    std::cout << std::hex << i << std::endl;
    std::cout << std::hex << u << std::endl;
    std::cout << std::hex << c << std::endl;
    std::cout << std::hex << b << std::endl;
    return 0;
}

输出

b7
b7
�
�

我怀疑这个输出在Windows(非UTF-8)系统上有所不同。