自学内容网 自学内容网

[C++] bitset 按字节解析为std::string

#include <iostream>
#include <string>
#include <cstring>
#include <bitset>

int main() {
    // 假设 4 个 char 存储了 32 位的 1
    //char charArray[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
    char charArray[4] = { 0x41, 0x42, 0x43, 0x44 };  // 对应字符 'A', 'B', 'C', 'D'

    // 将 char 数组转换为 std::string
    std::string str(charArray, 4);

    // 打印字符串的每个字符的十六进制值
    for (unsigned char c : str) {
        std::cout << std::hex << static_cast<int>(c) << " ";
    }
    std::cout << std::endl;
    std::cout << str << std::endl;// ABCD


    // 将 charArray 转换为 32 位的 bitset
    std::bitset<32> bitset3;
    for (int i = 0; i < 4; ++i) {
        std::bitset<8> charBits(charArray[i]);
        for (int j = 0; j < 8; ++j) {
            bitset3[i * 8 + j] = charBits[j];
        }
    }

    // 打印 bitset
    std::cout << "bitset: " << bitset3 << std::endl;

    // 假设我们有一个 32 位的 bitset
    std::bitset<32> bitset2("01000100010000110100001001000001");  // 示例 bitset

    // 将 bitset 转换为字符串
    std::string bitsetString = bitset2.to_string();

    // 打印字符串
    std::cout << "bitset as string: " << bitsetString << std::endl;

    // 假设我们有一个 32 位的 bitset
    std::bitset<32> bitset("01000100010000110100001001000001");  // 示例 bitset

    // 将 bitset 按 8 位解析为 4 个字节的 std::string
    std::string byteString;
    for (int i = 0; i < 32; i += 8) {
        std::bitset<8> byteBits;
        for (int j = 0; j < 8; ++j) {
            byteBits[j] = bitset[i + j];
        }
        char byte = static_cast<char>(byteBits.to_ulong());
        byteString.push_back(byte);
    }

    // 打印结果
    std::cout << "byteString: " << byteString << std::endl;

    // 打印每个字符的十六进制值
    for (unsigned char c : byteString) {
        std::cout << std::hex << static_cast<int>(c) << " ";
    }
    std::cout << std::endl;


    return 0;
}

41 42 43 44
ABCD
bitset: 01000100010000110100001001000001
bitset as string: 01000100010000110100001001000001
byteString: ABCD
41 42 43 44


原文地址:https://blog.csdn.net/cxyhjl/article/details/142638762

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!