[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值