简体   繁体   English

使用sprintf打印六进制值的便携式方法

[英]Portable way of printing hexa values with sprintf

I've had some trouble with binary-to-(printable)hexa conversions. 我遇到了二进制到(可打印)六进制转换的麻烦。 I've reached a functional (for my system) way of writing the code, but I need to know if it is portable on all systems (OS & hardware). 我已经达到了一种功能(针对我的系统)编写代码的方式,但是我需要知道它是否可以在所有系统(操作系统和硬件)上移植

So this is my function (trying to construct a UUID from a piece of binary text): 所以这是我的功能(试图从一段二进制文本构造一个UUID):

int extractInfo( unsigned char * text )
{
    char h[3];
    int i;

    this->str.append( "urn:uuid:" );
    for( i = 56; i < 72; i++ )
    {
        ret = snprintf( h, 3, "%02x", text[i] );
        if( ret != 2 )
            return 1;
        this->str.append( h );
        if( i == 59 || i == 61 || i == 63 || i == 65 )
            this->str.append( "-" );
    }

    return 0;
}

I understood that because of the sign extension my values are not printed well if I use char instead of unsigned char ( C++ read binary file and convert to hex ). 我知道,由于使用了符号扩展名,如果我使用char而不是unsigned charC ++读取二进制文件并转换为hex ),则我的值不能很好地打印出来。 Accepted and modified respectively. 分别接受和修改。

But I've encountered more variants of doing this: Conversion from binary file to hex in C , and I am really lost. 但是我遇到了更多的变体: 在C中从二进制文件转换为十六进制 ,我真的迷失了。 In unwind's piece of code: 在展开代码中:

sprintf(hex, "%02x", (unsigned int) buffer[0] & 0xff);

I did not understood why, although the array is unsigned char (as defined in the original posted code, by the one who asked the question), a cast to an unsigned int is needed, and also a bitwise AND on the byte to be converted... 我不明白为什么,尽管数组是无符号的char(在原始发布的代码中定义,由提出问题的人定义),但需要强制转换为无符号的int ,并且还要对要转换的字节进行按位AND ...

So, as I did not understood very well the sign-extension thing, can you tell me at least if the piece of code I wrote will work on all systems? 因此,由于我不太了解符号扩展问题,您能否告诉我至少我编写的代码是否可以在所有系统上使用?

since printf is not typesafe it expects for each formatting specifier a special sized argument. 由于printf不是类型安全的,因此它希望每个格式说明符都有一个特殊大小的参数。 thatswhy you have to cast your character argument to unsigned int if you use some formatting character that expects an int-sized type. 那就是为什么如果您使用某些需要int大小类型的格式字符,则必须将character参数转换为unsigned int

The "%x" specifier requires an unsigned int. "%x"说明符需要一个无符号的int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM