简体   繁体   English

将负二进制数转换为十进制数

[英]Convert negative binary number to decimal

For example:例如:

string binaryValue = "11111111111111111111111111111011" // -5

I need to convert this string to decimal representatin of this number.我需要将此字符串转换为该数字的十进制表示。

stoi(binaryValue, nullptr, 2)

Will throw exception on this case.在这种情况下会抛出异常。 So how can i do this in c++ ?那么我怎样才能在 C++ 中做到这一点呢? String or int doesn't matter. String 或 int 无关紧要。

See the documentation of:请参阅以下文档

int  std::stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );

in particular:特别是:

The valid integer value [of str ] consists of the following parts: [of str ] 的有效整数值由以下部分组成:

  • (optional) plus or minus sign (可选)加号或减号

... ...

... ...

If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by unary minus in the result type.如果减号是输入序列的一部分,则从数字序列计算出的数值将被否定,就像结果类型中的一元减号一样。

Exceptions例外

  • std::invalid_argument if no conversion could be performed如果无法执行转换,则为std::invalid_argument

  • std::out_of_range if the converted value would fall out of the range of the result type...如果转换后的值超出结果类型的范围,则为std::out_of_range ...

In the absence of a preceding minus-sign, the string:在没有前面的减号的情况下,字符串:

std::string binaryValue = "11111111111111111111111111111011";

will be interpreted in a the call:将在调用中解释:

std::stoi(binaryValue, nullptr, 2);

as a non-negative integer value in base-2 representation.作为基数为 2 表示的非负整数值。 But as such, it is out of range, so std::out_of_range is thrown:但正因如此,它超出范围,因此抛出std::out_of_range

To represent -5 as a string that your std::stoi call will convert as you expect, use:要将 -5 表示为std::stoi调用将按预期转换的字符串,请使用:

std::string const binaryValue = "-101";

Live demo现场演示

If you don't want to prefix a minus sign to a non-negative base-2 numeral, or cannot do so in your real-world situation, but wish to interpret "11111111111111111111111111111011" as the two's complement representation of a signed integer using the std::sto* API, then you must first convert the string to an unsigned integer of a wide-enough type, and then convert that unsigned value to a signed one.如果您不想在非负基数为 2 的数字前加上减号,或者在您的实际情况中不能这样做,但希望将"11111111111111111111111111111011"解释为使用有符号整数的二进制补码表示std::sto* API,那么您必须首先将字符串转换为足够宽类型的无符号整数,然后将该无符号值转换为有符号值。 Eg例如

#include <string>
#include <iostream>

int main()
{
    auto ul = std::stoul("11111111111111111111111111111011",nullptr,2);
    std::cout << ul << std::endl;
    int i = ul;
    std::cout << i << std::endl;
    return 0;
}

Live demo现场演示

as you probably know number are stored as Twos Complement您可能知道数字存储为二进制补码
to convert it using simple pseudocode使用简单的伪代码转换它

flip numbers 0->1, 1->0 from left to write util you find last 1 in string don't toggle this one从左边翻转数字 0->1, 1->0 来写 util 你在字符串中找到最后一个 1 不要切换这个

this will be your answer 0000000000000000000000000101=5这将是你的答案 0000000000000000000000000101=5


here is the code brouht from https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/这是来自https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/的代码

#include<bits/stdc++.h>
using namespace std;


string findTwoscomplement(string str)
{


  int n = str.length();


// Traverse the string to get first '1' from
// the last of string
int i;
for (i = n ; i >= 0 ; i--)
    if (str[i] == '1')
        break;

// If there exists no '1' concat 1 at the
// starting of string
if (i == 0)
    return '1' + str;

// Continue traversal after the position of
// first '1'
for (int k = i-1 ; k >= 0; k--)
{
    //Just flip the values
    if (str[k] == '1')
        str[k] = '0';
    else
        str[k] = '1';
}

// return the modified string
return str;;
}



int main()
{
    string str = "11111111111111111111111111111011";
    cout << findTwoscomplement(str);
//now you convert it to decimal if you want
    cout<<"Hello World";
    cout << stoul( findTwoscomplement(str),nullptr,2);
        return 0;


     }  

preview at https://onlinegdb.com/SyFYLVtdfhttps://onlinegdb.com/SyFYLVtdf预览

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM