954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

decimal > binary > Oct > Hex

Would I have to go about doing the math manually and make my own function? Is there some built in function I can use to be lazy? Is there some totally easier way that I am oblivious to?

Transworld
Newbie Poster
14 posts since Apr 2004
Reputation Points: 11
Solved Threads: 0
 

I found this link , which you could use to do the decimal to hex number.

But, I'd imagine somewhere there's bound to be some kind of library function that could do this for you... Have you searched Google for it yet?

alc6379
Cookie... That's it
Team Colleague
2,820 posts since Dec 2003
Reputation Points: 186
Solved Threads: 147
 
Would I have to go about doing the math manually and make my own function? Is there some built in function I can use to be lazy? Is there some totally easier way that I am oblivious to?

I will assume you mean you would like to display the value of some integral type in decimal, binary, octal, and hexadecimal representations. Three out of four are available the lazy way, but you'll need to roll your own to display a binary representation.

#include <iostream> 
 
 template < typename T >
 inline T highbit(T& t)
 {
    return t = (((T)(-1)) >> 1) + 1;
 }
 
 template < typename T >
 std::ostream& bin(T& value, std::ostream &o)
 {
    for ( T bit = highbit(bit); bit; bit >>= 1 )
    {
 	  o << ( ( value & bit ) ? '1' : '0' );
    }
    return o;
 }
 
 
 int main() 
 {
    unsigned long value = 0x12345678;
    std::cout << "hex: " << std::hex << value << std::endl;
    std::cout << "dec: " << std::dec << value << std::endl;
    std::cout << "oct: " << std::oct << value << std::endl;
    std::cout << "bin: ";
    bin(value, std::cout);
    std::cout << std::endl;
    return 0; 
 }
 
 /* my output
 hex: 12345678
 dec: 305419896
 oct: 2215053170
 bin: 00010010001101000101011001111000
 */
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Yeah, I did search Google. Amazingly hard to find things sometimes... But thanks everyone.:cheesy:

Transworld
Newbie Poster
14 posts since Apr 2004
Reputation Points: 11
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You