【问题标题】:String to long array in C++字符串到 C++ 中的长数组
【发布时间】:2014-06-22 03:17:02
【问题描述】:

我知道可以像这样将字符串转换为字符数组:

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

【问题讨论】:

  • 该语言包括可以对位进行操作的运算符,包括移位(&lt;&lt;&gt;&gt;)和按位或(|)。

标签: c++ arrays string type-conversion long-integer


【解决方案1】:

试试下面的

#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

【讨论】:

    【解决方案2】:

    如果您的系统使用正确的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2020-10-01
      • 2014-10-16
      • 1970-01-01
      • 2016-03-05
      相关资源
      最近更新 更多