2013-09-30 245 views
0

我已經做了如何爲int以十六進制字符串轉換一些研究,發現一個answer,但是我需要的是一點點的不同,你可以在下面的代碼中看到:INT爲十六進制字符串(C++)

int addr = 5386; // 

    std::string buffer = "contains 0xCCCCCCCC as hex (non ASCII in the string)"; 
    size_t idx = 0; 
    idx = buffer.find("\xCC\xCC\xCC\xCC", idx); 
    if (idx != string::npos) buffer.replace(idx, 4, XXX); // here i want to put the addr variable but as 0x0000150A 

我需要做的是在addr變量轉換爲已在字節之間的\x等預先"\x0a\x15\x00\x00"

感謝一個十六進制字符串的方式。

+0

你看看http://stackoverflow.com/questions/15823597/use-printf-to-print-character-string-十六進制格式扭曲結果? – Thomas

+2

緩衝區包含八個字符'C'(0x43),但您搜索字符(0xCC)。這不匹配。你想實現什麼? – harper

+0

@harper nope,正如我寫的那樣,緩衝區實際上包含4個字節作爲'cc:cc:cc:cc' –

回答

2

也許這個方案將幫助您:

#include <sstream> 
#include <iomanip> 
#include <iostream> 

int main(int argc, char const *argv[]) 
{ 
    int a = 5386; 

    std::ostringstream vStream; 
    for(std::size_t i = 0 ; i < 4 ; ++i) 
     vStream << "\\x" 
       << std::right << std::setfill('0') << std::setw(2) << std::hex 
       << ((a >> i*4) & 0xFF); 

    std::cout << vStream.str() << std::endl; 

    return 0; 
} 

我不知道我正是得到了你的問題,但我知道你想一個int被轉換成格式的字符串:「\ XAA \ XAA \ XAA \ XAA」。

它使用std::right,std::setfill('0')std::setw(2)強制輸出「2」爲「02」。 std::hex是獲得一個整數的十六進制表示。

1

事情是這樣的:

char buf[20]; 
uint32_t val; 
sprintf(buf, "\\x%02x\\x%02x\\x%02x\\x%02x", 
     (val >> 24), (uint8_t)(val >> 16), (uint8_t)(val >> 8), (uint8_t)val); 
+1

不要忘記加倍斜線。 – Michael

1

您可能要正確對待addrchar*,但你將與排列順序問題。

你可能會像手工做的工作:

unsigned int addr = 5386 // 0x0000150A 

char addrAsHex[5] = {(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF, 0}; 

// ... 
buffer.replace(idx, 4, addrAsHex); 
相關問題