boostorg / boostorg/multiprecision

Binary string to cpp_int

Open
#297 9 comments 2 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
265
Forks
128
Avg merge
4h 48m
Merged PRs (30d)
2

Description

Hello, I noticed boost multiprecision does not have a binary string to decimal converter, so I made one. Hope you enjoy!
```c++
// credit: Alexios A Angel
// C++ program to convert binary to decimal
#include
#include

/******************************************************
* Function : cpp_int bin_2_dec(const std::string_view& num)
* Input : A string of ones and zeros
* Output : cpp_int
******************************************************
* Read digits left to right
* Ex.
* MSB LSB
* { '1', '1', '1', '0' }
* str index: 0 1 2 3
* bin index 3 2 1 0
*
* The bit index is inverse (displayed above) to the
* digits in the string, so the algorithm will be
*
* ┌──┬───────────────────────────────────────────────────────┐
* │1 │unsigned int bin_2_dec(const std::string_view& str) │
* │2 │{ │
* │3 │ unsigned int dec_value = 0; │
* │4 │ int len = str.size(); │
* │5 │ int bin_index = len - 1; │
* │6 │ int str_index = 0; │
* │7 │ │
* │8 │ for(; str_index < len; ++str_index, --bin_index){ │
* │9 │ dec_value |= (str[str_index] - '0') << bin_index;│
* │10│ } │
* │11│ return dec_value; │
* │12│} │
* └──┴───────────────────────────────────────────────────────┘
* You could say we are converting Little endian to Big endian.
* Unfortunately, if there are more than sizeof(int) digits in the string than the shift in Line 9
* will overflow. In order to get around this in boost mp we
* use boost::multiprecision::bit_set
*/

//change std::string_view to std::span if
//number of digits is greater than std::string_view{}.max_size()
boost::multiprecision::cpp_int bin_2_dec(const std::string_view& num)
{

boost::multiprecision::cpp_int dec_value = 0;
auto cptr = num.data();
auto len = num.size();
//check if big enough to have 0b postfix
if(num.size() > 2){
//check if 2nd character is the 'b' binary postfix
//skip over it & adjust length accordingly if it is
if(num[1] == 'b' || num[1] == 'B'){
cptr += 2;
len -= 2;
}
}

//change i's type to cpp_int if the number of digits is greater
//than std::numeric_limits::max()
for (size_t i = len - 1; 0 <= i; ++cptr, --i) {
if(*cptr == '1'){
boost::multiprecision::bit_set(/*.val = */ dec_value, /*.pos = */ i);
}
}
return dec_value;
}

// Driver program to test above function
int main()
{
//266 bits
std::cout << bin_2_dec(/*.num = */"0b11111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111111") << '\n';
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.