2013-07-15 28 views
4

我有一個std::string代表小端,十六進制形式的64位內存地址。如何將其轉換爲uint64_t表示?如何將64位地址的std :: string表示形式轉換爲uint64_t?

+0

可能重複( http://stackoverflow.com/questions/1484140/how-do-you-get-an-unsigned-long-out-of-a-string) –

+0

另請參閱http://stackoverflow.com/questions/5117844/c -string-streams –

+0

「小端,十六進制」究竟是什麼意思?在16位中,數字「0x1234」是由字符串「」4321「」還是「」3412「」表示的?(即它是字節式還是十六進制數字小端)? –

回答

3
#include <sstream> 
#include <string> 
#include <iostream> 
#include <iomanip> 
#include <cstdint> 

int main() 
{ 
    std::string s("0x12345"); 
    std::stringstream strm(s); 
    std::uint64_t n; 
    strm >> std::hex >> n; 
    std::cout << std::hex << n << std::endl; 
    return 0; 
} 

按預期打印12345

編輯:如果你想從little-endian的以大端轉換,這也是有可能的:?你如何獲得一個unsigned long出字符串]

#include <sstream> 
#include <string> 
#include <iostream> 
#include <iomanip> 
#include <algorithm> 
#include <cstdint> 

int main() 
{ 
    std::string s("0x12345"); 
    std::stringstream strm(s); 

    union { 
     std::uint64_t n; 
     std::uint8_t a[8]; 
    } u; 

    strm >> std::hex >> u.n; 
    std::reverse(u.a, u.a + 8); 

    std::cout << std::hex << std::setfill('0') << std::setw(16) << u.n << std::endl; 
    return 0; 
} 
+0

但字符串是小尾數,十六進制形式。例如,內存地址0x400678表示爲「7806400000000000」。 – RouteMapper

+1

@RouteMapper然後在轉換後交換字節。 – 2013-07-15 19:16:30

+0

是否有從uint64_t類型交換字節的衆所周知的功能? – RouteMapper