简体   繁体   English

为什么函数以相反的顺序显示十六进制代码?

[英]Why is the function displaying the hex code in reverse order?

The following code (in C++) is supposed to get some data along with it's size (in terms of bytes) and return the string containing the hexadecimal code. 以下代码(在C ++中)应该获取一些数据及其大小(以字节为单位)并返回包含十六进制代码的字符串。 size is the size of the memory block with its location stored in val . size是内存块的大小,其位置存储在val

std::string byteToHexString(const unsigned char* val, unsigned long long size)
{
    unsigned char temp;
    std::string vf;
    vf.resize(2 * size+1);
    for(unsigned long long i= 0; i < size; i++)
    {
        temp = val[i] / 16;
        vf[2*i] = (temp <= 9)? '0' + temp: 'A' + temp - 10; // i.e., (10 = 9  + 1)
        temp = val[i] % 16;

        vf[2*i+1] = (temp <= 9)? '0' + temp: 'A' + temp - 10; // i.e., (10 = 9  + 1)
   }

vf[2*size] = '\0';
return (vf);
}

So on executing the above function the following way: 所以在执行上述功能时有以下几种方式:

int main()
{
     unsigned int a = 5555;
     std::cout << byteToHexString((unsigned char*)(&a), 4);
    return 0; 
}

The output we obtain is: 我们获得的输出是:

B3150000

Shouldn't the output rather be 000015B3 ? 输出不应该是000015B3吗? So why is this displaying in reverse order? 那么为什么这个以相反的顺序显示呢? Is there something wrong with the code (I am using g++ compiler in Ubuntu)? 代码有问题(我在Ubuntu中使用g ++编译器)?

You are seeing the order in which bytes are stored for representing integers on your architecture, which happens to be little-endian . 您正在查看存储字节的顺序,以表示您的体系结构上的整数,这恰好是little-endian That means, the least-significant byte comes first. 这意味着,最不重要的字节首先出现。

If you want to display it in normal numeric form, you either need to detect the endianness of your architecture and switch the code accordingly, or just use a string stream: 如果要以普通数字形式显示它,则需要检测体系结构的字节顺序并相应地切换代码,或者只使用字符串流:

unsigned int a = 5555;
std::ostringstream ss;
ss << std::setfill( '0' ) << std::setw( sizeof(a)*2 ) << std::hex << a;
std::cout << ss.str() << std::endl;

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

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