2010-04-04 82 views
1

如何輸入DEADBEEF和輸出DEADBEEF作爲四個字節數組?字符串到字節數組

+0

需要'家庭作業'標籤? – 2010-04-04 19:08:49

回答

4
void hexconvert(char *text, unsigned char bytes[]) 
{ 
    int i; 
    int temp; 

    for(i = 0; i < 4; ++i) { 
     sscanf(text + 2 * i, "%2x", &temp); 
     bytes[i] = temp; 
    } 
} 
+0

謝謝。是工作。 – hlgl 2010-04-05 05:54:05

2

聽起來像要將字符串解析爲十六進制爲整數。 C++方式:

#include <iostream> 
#include <sstream> 
#include <string> 

template <typename IntType> 
IntType hex_to_integer(const std::string& pStr) 
{ 
    std::stringstream ss(pStr); 

    IntType i; 
    ss >> std::hex >> i; 

    return i; 
} 

int main(void) 
{ 
    std::string s = "DEADBEEF"; 
    unsigned n = hex_to_integer<unsigned>(s); 

    std::cout << n << std::endl; 
}