2014-05-05 26 views
2

多頭排列據我所知,一個可以將字符串轉換爲字符數組,像這樣:字符串在C++

string a = "abcdefgh"; 
char b[8]; 
strcpy(b, a.c_str()); 
cout << (int)b[3]; 

在這裏,我得到的輸出100

我的問題是:如何將字符串轉換爲數組long。我想知道如何將字符串「abcdefgh」轉換爲數組long b[2]。第一長(b[0])應該是長0x61626364,第二長(b[1])應該是0x65666768。如果這是有道理的。所以

cout << (unsigned int)b[0] 

應該輸出1001633837924

+0

語言包括下列可在比特操作符,包括移('<<', '>>')和按位或('|')。 –

回答

3

請嘗試以下

#include <iostream> 
#include <iomanip> 
#include <string> 

int main() 
{ 
    std::string s("abcdefgh"); 
    long b[2] = {}; 

    for (std::string::size_type i = 0, j = 0; i < 2 && j < s.size(); j++) 
    { 
     b[i] = b[i] << 8 | (unsigned char)s[j]; 
     if (j % sizeof(long) == sizeof(long) - 1) i++; 
    } 

    std::cout << std::hex << b[0] << '\t' << b[1] << std::endl; 

    return 0; 
} 

輸出是

61626364 65666768 

這將是甚至更好替代聲明

 if (j % sizeof(long) == sizeof(long) - 1) i++; 

 if (j % sizeof(*b) == sizeof(*b) - 1) i++; 

在這種情況下,你可以改變B的類型而無需更改任何其他代碼。例如

#include <iostream> 
#include <iomanip> 
#include <string> 

int main() 
{ 
    std::string s("abcdefgh"); 
    long long b[2] = {}; 

    for (std::string::size_type i = 0, j = 0; i < 2 && j < s.size(); j++) 
    { 
     b[i] = b[i] << 8 | (unsigned char)s[j]; 
     if (j % sizeof(*b) == sizeof(*b) - 1) i++; 
    } 

    std::cout << std::hex << b[0] << '\t' << b[1] << std::endl; 

    return 0; 
} 

輸出是

6162636465666768 0 
+0

謝謝你。 – Thomas

1

如果您的系統使用正確的endianess,則可以使用reinterpret_cast

例如(這不是你期望的輸出):

std::string a = "abcdefgh"; 
const long* b = reinterpret_cast<const long*>(a.data()); 
std::cout << std::hex << b[0] << " " << b[1] << std::endl; 
// 64636261 68676665 

如果你想獲得另外一個,你必須自己編寫代碼或使用字節交換操作。例如用MSVC:

#include<Bits.h> 
// .... 
std::cout << std::hex << _byteswap_ulong(b[0]) << " " << b[1] << std::endl; 
// 61626364 68676665 

可以很容易地建立與std::transform結果:

std::string a = "abcdefgh"; 
const long* b = reinterpret_cast<const long*>(a.data()); 
long c[2]; 
std::transform(b, b+2, c, _byteswap_ulong); 
std::cout << std::hex << c[0] << " " << c[1] << std::endl; 
// 61626364 65666768