c++ stl二进制转换_使用C ++ STL中的stoi()函数将二进制字符串转换为整数

c++ stl二进制转换

Given a binary string, we have to convert it into an integer using stoi() function.

给定一个二进制字符串,我们必须使用stoi()函数将其转换为整数。

C ++ STL stoi()函数 (C++ STL stoi() function)

stoi() stands for string to integer, it is a standard library function in C++ STL, it is used to convert a given string in various formats (like binary, octal, hex or a simple number in string formatted) into an integer.

stoi()表示将字符串转换为整数 ,它是C ++ STL中的标准库函数,用于将各种格式(例如二进制,八进制,十六进制或字符串格式的简单数字)的给定字符串转换为整数。

Syntax:

句法:

    int stoi (const string&  str, [size_t* idx], [int base]);

Parameters:

参数:

  • const string& str is an input string.

    const string&str是输入字符串。

  • size_t* idx is an optional parameter (pointer to the object whose value is set by the function), it's default value is 0 or we can assign it to nullptr.

    size_t * idx是一个可选参数(指向由函数设置值的对象的指针),其默认值为0或我们可以将其分配给nullptr 。

  • int base is also an optional parameter, its default is 10. It specifies the radix to determine the value type of input string (2 for binary, 8 for octal, 10 for decimal and 16 for hexadecimal).

    int base也是一个可选参数,默认值为10。它指定基数来确定输入字符串的值类型(二进制为2,八进制为8,十进制为10,十六进制为16)。

Return value: It returns converted integer value.

返回值:返回转换后的整数值。

Example:

例:

    Input:
    string bin_string = "10101010";

    Function call:
    stoi(bin_string, 0, 2);

    Output:
    170

C ++ STL代码将二进制字符串转换为整数 (C++ STL code to convert a binary string into an integer )

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string bin_string = "10101010";
	int number =0;

	number = stoi(bin_string, 0, 2);
	cout<<"bin_string: "<<bin_string<<endl;
	cout<<"number: "<<number<<endl;

	bin_string = "111100001100111010";
	number = stoi(bin_string, 0, 2);
	cout<<"bin_string: "<<bin_string<<endl;
	cout<<"number: "<<number<<endl;

	return 0;
}

Output

输出量

bin_string: 10101010
number: 170
bin_string: 111100001100111010
number: 246586

Reference: std::stoi()

参考: std :: stoi()

翻译自: https://www.includehelp.com/stl/convert-binary-string-to-integer-using-stoi-function-in-cpp-stl.aspx

c++ stl二进制转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值