473,246 Members | 1,481 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

Converting between number bases

Is there an elegant way of converting strings containing digits
between different number bases in C++?

I.e.:
10 (base 2) = 2 (base 10)
FF (base 16) = 256 (base 10)
F (base 16) = 1111 (base 2) etc?

Thanks,
Alex
--
http://www.munted.org.uk

Take a nap, it saves lives.
Aug 8 '06 #1
2 4765
Alex Buell wrote:
Is there an elegant way of converting strings containing digits
between different number bases in C++?

I.e.:
10 (base 2) = 2 (base 10)
FF (base 16) = 256 (base 10)
F (base 16) = 1111 (base 2) etc?
Convert it to internal rep through 'stringstream' by inputting and
then output it again, using the other base. Or, you can write your
own conversion routine, which can be made a bit faster...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 8 '06 #2

"Alex Buell" <al********@munted.org.ukwrote:
Is there an elegant way of converting strings containing digits
between different number bases in C++?
Below I present excerpts from some earlier posts of mine in this group around
July 2 to July 5 of this year, in which I give a function which prints any
integer up to nine quintillion in any base from 2 to 30.

That's not exactly what you asked for, but it's close. If you can
write the part that converts from any base to a basic 2's-compliment
C++ integer variable, then you can use my function to print the
representation of that integer in the base of your choice.
//============= BEGIN EXCERPTS FROM EARLIER POSTS =====================

// July 2-5:

....For your enjoyment, a function that expresses any integer with
absolute value less-than-or-equal-to nine quintillion in any
base from 2 to 36...

.... if you don't like the non-std type "long long" you can always
change it to "long"; but then it could only handle numbers up to
about 2 billion, instead of 9 quintillion...

// Put this in a header file:

namespace YourNamespaceName
{

///////////////////////////////////////////////////////////////////////////
// //
// Base //
// Represent an integer in any base from 2 to 36. //
// //
///////////////////////////////////////////////////////////////////////////

template<typename T>
std::string
Base
(
int base, // must be >= 2 and <= 36
int precision, // must be >= 1 and <= 63
T number, // must be >= min+5 and <= max-5 for type
bool leading_zeros = false // does user want leading zeros?
)
{
T const max = std::numeric_limits<T>::max() - 5;
T const min = std::numeric_limits<T>::min() + 5;
double largest = pow(base, precision) - 1;
if
(
base < 2 || base 36 // If base is out-of-range
|| precision < 1 || precision 63 // or precision is out-of-range
|| number < min || number max // or number is out-of-range
|| largest max // or base/precision combo is out-of-range
|| largest < number // or base/precision combo can't express number
)
{
return std::string("***ERROR***"); // then return "***ERROR***".
}

std::string repre = std::string("");
if (number < 0)
{
number = -number;
repre += '-';
}

T place = 1;
for (int i = 1; i <= precision - 1; ++i)
{
place *= base;
}

T value = 0;
const char digits[37] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
bool first_non_zero = false;
for ( ; place 0; place /= base)
{
value = number / place;
if (value 0) first_non_zero = true;
if (leading_zeros || first_non_zero) repre += digits[value];
number -= value * place;
}
return repre;

} // end Base()

} // end namespace YourNamespaceName
//============= END EXCERPTS FROM EARLIER POSTS =====================

--
Cheers,
Robbie Hatley
Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
home dot pac bell dot net slant earnur slant
Aug 8 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Sven Mayer | last post by:
Assume a database (e.g. Oracle) field is declared as a) NUMBER (length=10) b) NUMBER (length=26) c) VARCHAR2 (length=1) d) VARCHAR2 (length=50) e) DATE How do I retrieve the contents from...
3
by: HumanJHawkins | last post by:
Hi, I have two tables. One of them has a text field, and the other has a numeric (integer) field that serves a similar purpose. I want to connect (UNION actually) the two tables, and store the...
5
by: Mukesh Kumar | last post by:
hi I am trying to pass range parameters to crystal reports from my .net environment. The start and end values of the range parameters are of currency type. I need to convert the number to currency...
1
by: ltamisin | last post by:
Hi Im Leo I want to convert a number to percentage, is there any built-in function for this? Thanks
2
by: Robert Fitzpatrick | last post by:
I searched through the net quickly and the list archives, but could not find anything doing this. Is it possible? There is a Perl module for doing this, but I guess cannot use modules for security...
2
by: mac | last post by:
Assume you have a textbox named "displayValue" What is the difference (if any) between these two approaches: 1.) float var; var = 0.42F; displayValue.Text = var.ToString 2.)
7
anukagni
by: anukagni | last post by:
Hi friends, I want to get this thing happen.. I want to convert the number to word i.e. if i entry 1 in an text box then it should give the reflect to One in an lable .. Is this possible...
5
by: ria3 | last post by:
Hi, I have to write a program that will alow the user to specify a number (decimal, binary, or hexadecimal) and a base to convert to (decimal, binary, or hexadecimal) using subroutine methods and...
0
by: Tania Louie | last post by:
Hi, I just need help coverting a number to a time in SQL. Currently it is returning a number of 1260 for the time and I need it to show as the actual time of 9:30. Not sure what to use here....
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.