数字与字符串转换

本文介绍了如何在C++中实现从十进制、十六进制、八进制到二进制及反之的转换函数,包括使用`to_string`、`stringstream`、`bitset`和`stoi`等方法。
/*
 * 数字与字符串转换练习
 */

#include<iostream>
#include<string>
#include<sstream>
#include<iomanip>
#include<bitset>

using namespace std;

void DecToStr()
{
	int num = 85932;
	string result = to_string(num);
	cout << "result: " << result << endl;
}

void HexToStr()
{
	int num = 0x56A4;
	stringstream ss;
	// std::setw(n), if num.size() > n, length = num.size()
	// else length = n
	ss << std::hex << std::setw(10) << std::setfill('0') << num;
	string result = ss.str();
	cout << "result: " << result << endl;
}

void OctToStr()
{
	int num = 05673;
	stringstream ss;
	ss << std::oct << std::setw(2) << std::setfill('0') << num;
	string result = ss.str();
	cout << "result: " << result << endl;
}

void BinToStr()
{
	// bitset 限制长度
	int num = 0b100111;
	bitset<10> temp(num);
	string result = temp.to_string();
	cout << "result: " << result << endl;
}

/* bitset 提供了指定长度的二进制输出,
 * 但是对于不知道有多长的数字来说,使用起来不太理想
 */
void BigBinToStr()
{
	int num = 0b101000110100111;

	int rem = 0;
	int modTemp = 1;
	string result = "0b";
	while (modTemp != 0) {
		modTemp = num / 2;
		rem = num % 2;
		num = modTemp;
		result.insert(2, to_string(rem));
	}
	cout << "result: " << result << endl;

}

// 二进制转十六进制
void BinToHex() {
	int num = 0b101000110100111;
	stringstream ss;
	ss << std::hex << num;
	string result = ss.str();
	cout << "result: " << result << endl;
}

void StrToHex() {
	string numStr = "0x51a7";
	int result = stoi(numStr, 0, 16);
	cout << "result: " << std::hex << std::uppercase << result << endl;
}

void StrToOct() {
	string numStr = "076547";
	int result = stoi(numStr, 0, 8);
	cout << "result: " << std::oct << result << endl;
}

void StrToDec() {
	string numStr = "123456";
	int result = stoi(numStr, 0, 10);
	cout << "result: " << result << endl;
}

void StrToBin() {
	string numStr = "11011001";  // 不能用 0b 开头
	int result = stoi(numStr, 0, 2);
	cout << "result: " << result << endl;
}


int main()
{
	StrToBin();
	return 0;
}

十进制转二进制

// 用一个案例展示
#include <vector>
#include <iostream>
#include <bitset>

using namespace std;

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> result;
        for (int i = 0; i < n; ++i) {
            bitset<32> binary(i);
            string tmp = binary.to_string();
            auto first1 = tmp.find_first_of('1');
            int curCount = 0;
            for (int c = first1; c < tmp.size(); ++c) {
                if (tmp[c] == '1') {
                    curCount++;
                }
            }
            result.push_back(curCount);
        }
        return result;
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值