Can anybody give an example of c++ code that can easily convert a decimal value to binary and a binary value to decimal please?
Well, your question is really vague, so this answer is the same.
string DecToBin(int number)
{
if ( number == 0 ) return "0";
if ( number == 1 ) return "1";
if ( number % 2 == 0 )
return DecToBin(number / 2) + "0";
else
return DecToBin(number / 2) + "1";
}
int BinToDec(string number)
{
int result = 0, pow = 1;
for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
result += (number[i] - '0') * pow;
return result;
}
You should check for overflow and do input validation of course.
x << 1 == x * 2
Here's a way to convert to binary that uses a more "programming-like" approach rather than a "math-like" approach, for lack of a better description (the two are actually identical though, since this one just replaces divisions by right shifts, modulo by a bitwise and, recursion with a loop. It's kind of another way of thinking about it though, since this makes it obvious you are extracting the individual bits).
string DecToBin2(int number)
{
string result = "";
do
{
if ( (number & 1) == 0 )
result += "0";
else
result += "1";
number >>= 1;
} while ( number );
reverse(result.begin(), result.end());
return result;
}
And here is how to do the conversion on paper:
Decimal to binary
Binary to decimal
strtol will convert a binary string like "011101" to an internal value (which will normally be stored in binary as well, but you don't need to worry much about that). A normal conversion (e.g. operator<< with std:cout) will give the same value in decimal.
//The shortest solution to convert dec to bin in c++
void dec2bin(int a) {
if(a!=0) dec2bin(a/2);
if(a!=0) cout<<a%2;
}
int main() {
int a;
cout<<"Enter the number: "<<endl;
cin>>a;
dec2bin(a);
return 0;
}
I assume you want a string to binary conversion?
template<typename T> T stringTo( const std::string& s )
{
std::istringstream iss(s);
T x;
iss >> x;
return x;
};
template<typename T> inline std::string toString( const T& x )
{
std::ostringstream o;
o << x;
return o.str();
}
use these like this:
int x = 32;
std:string decimal = toString<int>(x);
int y = stringTo<int>(decimal);
Related
I want to do basic arithmetic (addition, subtraction and comparison) with 64 digit hex numbers represented as strings. for example
"ffffa"+"2" == "ffffc"
Since binary representation of such a number requires 256 bits, I cannot convert the string to basic integer types. one solution is to use gmp or boost/xint but they are too big for this simple functionality.
Is there a lightweight solution that can help me?
Just write a library which will handle the strings with conversion between hex to int and will add one char at a time, taking care of overflow. It took minutes to implement such an algorithm:
#include <cstdio>
#include <sstream>
#include <iostream>
using namespace std;
namespace hexstr {
char int_to_hexchar(int v) {
if (0 <= v && v <= 9) {
return v + '0';
} else {
return v - 10 + 'a';
}
}
int hexchar_to_int(char c) {
if ('0' <= c && c <= '9') {
return c - '0';
} else {
return c - 'a' + 10;
}
}
int add_digit(char a, char b) {
return hexchar_to_int(a) + hexchar_to_int(b);
}
void reverseStr(string& str) {
int n = str.length();
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
void _add_val_to_string(string& s, int& val) {
s.push_back(int_to_hexchar(val % 16));
val /= 16;
}
string add(string a, string b)
{
auto ita = a.end();
auto itb = b.end();
int tmp = 0;
string ret;
while (ita != a.begin() && itb != b.begin()) {
tmp += add_digit(*--ita, *--itb);
_add_val_to_string(ret, tmp);
}
while (ita != a.begin()) {
tmp += hexchar_to_int(*--ita);
_add_val_to_string(ret, tmp);
}
while (itb != b.begin()) {
tmp += hexchar_to_int(*--itb);
_add_val_to_string(ret, tmp);
}
while (tmp) {
_add_val_to_string(ret, tmp);
}
reverseStr(ret);
return ret;
}
}
int main()
{
std::cout
<< "1bd5adead01230ffffc" << endl
<< hexstr::add(
std::string() + "dead0000" + "00000" + "ffffa",
std::string() + "deaddead" + "01230" + "00002"
) << endl;
return 0;
}
This can be optimized, the reversing string maybe can be omitted and some cpu cycles and memory allocations spared. Also error handling is lacking. It will work only on implementations that use ASCII table as the character set and so on... But it's as simple as that. I guess this small lib can handle any hex strings way over 64 digits, depending only on the host memory.
Implementing addition, subtraction and comparison over fixed-base numeric strings yourself should be quite easy.
For instance, for addition and subtraction, simply do it as you would in paper: start on the right-hand end of both strings, parse the chars, compute the result, then carry over, etc. Comparison is even easier, and you go left-to-right.
Of course, all this is assuming you don't need performance (otherwise you should be using a proper library).
I am currently using the code below that removes all digits equal to zero from an integer.
int removeZeros(int candid)
{
int output = 0;
string s(itoa(candid));
for (int i = s.size(); i != 0; --i)
{
if (s[i] != '0') output = output * 10 + atoi(s[i]);
}
return output;
}
The expected output for e.g. 102304 would be 1234.
Is there a more compact way of doing this by directly working on the integer, that is, not string representation? Is it actually going to be faster?
Here's a way to do it without strings and buffers.
I've only tested this with positive numbers. To make this work with negative numbers is an exercise left up to you.
int removeZeros(int x)
{
int result = 0;
int multiplier = 1;
while (x > 0)
{
int digit = x % 10;
if (digit != 0)
{
int val = digit * multiplier;
result += val;
multiplier *= 10;
}
x = x / 10;
}
return result;
}
For maintainability, I would suggest, don't work directly on the numeric value. You can express your requirements in a very straightforward way using string manipulations, and while it's true that it will likely perform slower than number manipulations, I expect either to be fast enough that you don't have to worry about the performance unless it's in an extremely tight loop.
int removeZeros(int n) {
auto s = std::to_string(n);
s.erase(std::remove(s.begin(), s.end(), '0'), s.end());
return std::stoi(s);
}
As a bonus, this simpler implementation handles negative numbers correctly. For zero, it throws std::invalid_argument, because removing all zeros from 0 doesn't produce a number.
You could try something like this:
template<typename T> T nozeros( T const & z )
{
return z==0 ? 0 : (z%10?10:1)*nozeros(z/10)+(z%10);
}
If you want to take your processing one step further you can do a nice tail recursion , no need for a helper function:
template<typename T> inline T pow10(T p, T res=1)
{
return p==0 ? res : pow10(--p,res*10);
}
template<typename T> T nozeros( T const & z , T const & r=0, T const & zp =0)
{
static int digit =-1;
return not ( z ^ r ) ? digit=-1, zp : nozeros(z/10,z%10, r ? r*pow10(++digit)+zp : zp);
}
Here is how this will work with input 32040
Ret, z, r, zp, digits
-,32040,0,0, -1
-,3204,0,0, -1
-,320,4,0,0, -1
-,32,0,4,4, 0
-,3,2,4, 0
-,0,3,24, 1
-,0,0,324, 2
324,-,-,-, -1
Integer calculations are always faster than actually transforming your integer to string, making comparisons on strings, and looking up strings to turn them back to integers.
The cool thing is that if you try to pass floats you get nice compile time errors.
I claim this to be slightly faster than other solutions as it makes less conditional evaluations which will make it behave better with CPU branch prediction.
int number = 9042100;
stringstream strm;
strm << number;
string str = strm.str();
str.erase(remove(str.begin(), str.end(), '0'), str.end());
number = atoi(str.c_str());
No string representation is used here. I can't say anything about the speed though.
int removezeroes(int candid)
{
int x, y = 0, n = 0;
// I did this to reverse the number as my next loop
// reverses the number while removing zeroes.
while (candid>0)
{
x = candid%10;
n = n *10 + x;
candid /=10;
}
candid = n;
while (candid>0)
{
x = candid%10;
if (x != 0)
y = y*10 + x;
candid /=10;
}
return y;
}
If C++11 is available, I do like this with lambda function:
int removeZeros(int candid){
std::string s=std::to_string(candid);
std::string output;
std::for_each(s.begin(), s.end(), [&](char& c){ if (c != '0') output += c;});
return std::stoi(output);
}
A fixed implementation of g24l recursive solution:
template<typename T> T nozeros(T const & z)
{
if (z == 0) return 0;
if (z % 10 == 0) return nozeros(z / 10);
else return (z % 10) + ( nozeros(z / 10) * 10);
}
I am trying to better understand how 'big numbers' libraries work, (like GMP for example).
I want to write my own function to Add() / Subtract() / Multiply() / Divide()
The class is traditionally defined ...
std::vector<unsigned char> _numbers; // all the numbers
bool _neg; // positive or negative number
long _decimalPos; // where the decimal point is located
// so 10.5 would be 1
// 10.25 would be 2
// 10 would be 0 for example
First I need to normalise the numbers so I can do
Using 2 numbers
10(x) + 10.25(y) = 20.25
For simplicity, I would make them the same length,
For x:
_numbers = (1,0,0,0) decimal = 2
For y:
_numbers = (1,0,2,5) decimal = 2
And I can then reverse add x to y in a loop
...
// where x is 10.00 and y is 10.25
...
unsigned char carryOver = 0;
int totalLen = x._numbers.size();
for (size_t i = totalLen; i > 1 ; --i )
{
unsigned char sum = x._numbers[i-1] + y._numbers[i-1] + carryOver;
carryOver = 0;
if (sum > _base)
{
sum -= _base;
carryOver = 1;
}
numbers.insert( number.begin(), sum);
}
// any left over?
if (carryOver > 0)
{
numbers.insert( number.begin(), 1 );
}
// decimal pos is the same for this number as x and y
...
The example above will work for adding two positive numbers, but will soon fall over once I need to add a negative number to a positive number.
And this gets more complicated when it comes to subtracting numbers, then even worse for multiplications and divisions.
Can someone suggest some simple functions to Add() / Subtract() / Multiply() / Divide()
I am not trying to re-write / improve libraries, I just want to understand how they work with numbers.
addition and substractions are pretty straightforward
You need to inspect signs and magnitudes of operands and if needed convert the operation to/from +/-. Typical C++ implementation of mine for this is like this:
//---------------------------------------------------------------------------
arbnum arbnum::operator + (const arbnum &x)
{
arbnum c;
// you can skip this if you do not have NaN or Inf support
// this just handles cases like adding inf or NaN or zero
if ( isnan() ) return *this;
if (x.isnan() ) { c.nan(); return c; }
if ( iszero()) { c=x; return c; }
if (x.iszero()) return *this;
if ( isinf() ) { if (x.isinf()) { if (sig==x.sig) return *this;
c.nan(); return c; } return *this; }
if (x.isinf()) { c.inf(); return c; }
// this compares the sign bits if both signs are the same it is addition
if (sig*x.sig>0) { c.add(x,this[0]); c.sig=sig; }
// if not
else{
// compare absolute values (magnitudes)
if (c.geq(this[0],x)) // |this| >= |x| ... return (this-x)
{
c.sub(this[0],x);
c.sig=sig; // use sign of the abs greater operand
}
else { // else return (x-this)
c.sub(x,this[0]);
c.sig=x.sig;
}
}
return c;
}
//---------------------------------------------------------------------------
arbnum arbnum::operator - (const arbnum &x)
{
arbnum c;
if ( isnan() ) return *this;
if (x.isnan() ) { c.nan(); return c; }
if ( iszero()) { c=x; c.sig=-x.sig; return c; }
if (x.iszero()) return *this;
if ( isinf() ) { if (x.isinf()) { if (sig!=x.sig) return *this;
c.nan(); return c; } return *this; }
if (x.isinf()) { c.inf(); c.sig=-x.sig; return c; }
if (x.sig*sig<0) { c.add(x,this[0]); c.sig=sig; }
else{
if (c.geq(this[0],x))
{
c.sub(this[0],x);
c.sig=sig;
}
else {
c.sub(x,this[0]);
c.sig=-x.sig;
}
}
return c;
}
//---------------------------------------------------------------------------
where:
geq is unsigned comparison greater or equal
add is unsigned +
sub is unsigned -
division is a bit more complicated
see:
bignum divisions
approximational bignum divider
For divisions you need to have already implemented things like +,-,*,<<,>> and for some more advanced approaches you need even things like: absolute comparison (you need them for +/- anyway) , sqr, number of used bits usually separate for fractional and integer part.
The most important is the multiplication see Fast bignum square computation because it is core for most division algorithms.
performance
for some hints see BigInteger numbers implementation and performance
text conversion
If your number is in ASCII or in BASE=10^n digits then this is easy but If you use BASE=2^n instead for performance reasons then you need to have fast functions capable of converting between dec and hex strings so you can actually load and print some numbers to/from your class. see:
How do I convert a very long binary number to decimal?
How to convert a gi-normous integer (in string format) to hex format?
I am trying to convert a bit string (bitString) of length 'sLength' to an int.
The following code works fine for me in my computer. Is there any case where it may not work?
int toInt(string bitString, int sLength){
int tempInt;
int num=0;
for(int i=0; i<sLength; i++){
tempInt=bitString[i]-'0';
num=num+tempInt * pow(2,(sLength-1-i));
}
return num;
}
Thanks in advance
pow works with doubles. Result may be inaccurate. Use bit arithmetic instead
num |= (1 << (sLength-1-i)) * tempInt;
Don't also forget about cases when bitString contains symbols other than '0' and '1' or too long
Or, you can let the standard library do the heavy lifting:
#include <bitset>
#include <string>
#include <sstream>
#include <climits>
// note the result is always unsigned
unsigned long toInt(std::string const &s) {
static const std::size_t MaxSize = CHAR_BIT*sizeof(unsigned long);
if (s.size() > MaxSize) return 0; // handle error or just truncate?
std::bitset<MaxSize> bits;
std::istringstream is(s);
is >> bits;
return bits.to_ulong();
}
Why not change your for loop to the more efficient and far more simple C++11 version:
for (char c : bitString)
num = (num << 1) | // Shift the current set of bits to the left one bit
(c - '0'); // Add in the current bit via a bitwise-or
By the way, you should also check that the number of bits specified does not overrun an int and you may want to make sure that each char in the string is either a '0' or '1'.
Answer and notice about inaccuracy of floating-point numbers already given; here's a more readable implementation with integer arithmetic, though:
int toInt(const std::string &s)
{
int n = 0;
for (int i = 0; i < s.size(); i++) {
n <<= 1;
n |= s[i] - '0';
}
return n;
}
Notes:
You don't need an explicit length. That's why we have std::string::length().
Counting from zero results in cleaner code, because you don't have to do the subtraction every time.
for (std::string::reverse_iterator it = bitString.rbegin();
it != bitString.rend(); ++it) {
num *= 2;
num += *it == '1' ? 1 : 0;
}
I see directly three cases where it may not work :
pow Works with double, your result may be inaccurate, you can fix it with :
num |= tempInt * ( 1 << ( sLength - 1 - i ) );
If bitString[i] is not a '0' or '1',
If your number in the string in bigger than the int limit.
If you have control over the last two points, your resulting code could be :
int toInt( const string& bitString )
{
int num = 0;
for ( char c : bitString )
{
num <<= 1;
num |= ( c - '0' );
}
return num;
}
Don't forget the const reference as a parameter.
All I really know is PHP and I used the decbin function etc, It was fairly easy to do. In this C++ program I want to do the same thing, just a simple number or string how would I do this?
A simple function could be defined such as this:
void binary(int decimal) {
int remainder;
if(decimal <= 1) {
std::cout << decimal;
return;
}
remainder = decimal % 2;
binary(decimal >> 1);
std::cout << remainder;
}
Although there are many other resources on the web on how to do this..
A noteworthy question for efficiency of it here, as you may want more than just that:
Efficiently convert between Hex, Binary, and Decimal in C/C++
you can do this non-recursively using something like this:
std::string Dec2Bin(int nValue, bool bReverse = false)
{
std::string sBin;
while(nValue != 0)
{
sBin += (nValue & 1) ? '1' : '0';
nValue >>= 1;
}
if(!bReverse)
std::reverse(sBin.begin(),sBin.end());
return sBin;
}
of course this isn't too architucture friendly, but it avoids cout, just incase your not using a console. it also outputs in any bit ordering.
You can use itoa if it's available on your compiler. Just remember it's not standard and if you need a standard method you're better off using the other solutions posted.
If you want to print it, just use this code here. If you want to return a string, instead of using cout, append to a C++ string instead.
offering the iterative approach (pardon the #defines (but i'm quite sure they will be compiled to the expression's value), i don't quite remember predefined macro/constants in C):
#define INT_ARCH 32
#define ARCH_SHIFTABLE (INT_ARCH - 1)
#define ARCH_MAX_INT 1 << ARCH_SHIFTABLE
void dec_to_bin(int decimal)
{
int shifter = ARCH_MAX_INT;
for(; shifter > 0; shifter >>= 1)
cout << (decimal & shifter);
}
Similar to #Necrolis answer without the need for an if, and the reversal of the string.
string decimalToBinary(int decimal) {
string binary;
while(decimal) {
binary.insert(0, 1, (decimal & 1) + '0');
decimal >>= 1;
}
return binary;
}
Do with simple way in c++
#include <iostream>
using namespace std;
int main()
{
long n, rem, binary=0, i=1;
cout<<"Enter a int: ";
cin>>n;
while(n != 0)
{
rem = n%2;
n = n/2;
binary= binary + (rem*i);
i = i*10;
}
cout<< "\nAns: "<<binary <<endl;
return 0;
}