2017-06-04 42 views
1

我需要一些脚本帮助。我有十六进制数字,我需要对齐他们,但我不知道如何解决这个在c + +中很好的方式。对齐它们旁边的十六进制数字

比如我有此数组:

int test[3]={0x12,0x13,0xab}; 

所以,我想有这样的输出:

0x1213ab 

回答

0

您可以轻松地做到这一点

#include <iostream> 
#include <iomanip> 

int main() { 
    int test[3] = {0x12,0x13,0xab}; 

    std::cout << "0x"; 
    for(auto x : test) { 
     std::cout << std::hex << std::setw(2) << std::setfill('0') << x; 
        // |   |    | 
        // |   |    v 
        // |   |    Prevents filling blanks 
        // |   v 
        // |   Chooses a field output size of 2 
        // v 
        // Provides hex formatting of integers 
    } 
    std::cout << std::endl; 
} 

Live Demo

从好的个

相关链接:

+0

是有可能输出传递一个整数? – Yann

+0

@Yann是的,只是使用'std :: istream'和'std :: hex' I/O操纵器相同。但有更快的方法,在内存中做一个简单的拷贝。 –