Artician Home
Join Artician Login Search

kman's blog

avatar
  • kman
  • Male
  • Is Offline
  • Status: Administrator
  • Blog Views: 9983
  • Last Seen: 2 weeks ago

Profile

kman's Info
  • Joined: 08/25/06
  • Account: Artician Pro
  • Visits: 9983
  • Total Discussion Posts: 439
  • Portfolio Count: 15 | View
  • Blog Entries Count: 84 | View
  • Favorites Received: 25
  • Watchers: 19
Professional
Personal
Social Networks
Category: Computers & Internet - Programming & Web Development
Monday May 7th, 2007
The internet is full of over complicated code examples when it comes to displaying things in binary or octal or whatever.

So here are some very light recursive functions that will convert almost any generic datatype into it's appropriate base.

void toBinary(byte t)
{
if(t)
{
toBinary(t>>1);
cout << (t & 1);
}
}


Binary is the simplest conversion since you simply compare the 1s and 0s.

void toOctal(byte t)
{
cout << '0';
toOctalR(t);
}
void toOctalR(byte t)
{

if(t)
{
toOctalR(n>>3);
cout << (n & 7);
}

}

void toHex(int n)
{
cout << "0x";
toHexR(n);
}


Hex conversions are probably the hardest since you would need to call forth different alpha characters to represent 10, 11, 12, 13, 14, and 15. You could do a switch but this seems a bit more elegant imo.

void toHexR(int n)
{
if(n)
{
toHexR(n>>4);

if((n & 15) < 10)
cout << (n & 15);
else
cout << static_cast<char>((n & 15) + 55);
}
}


The +55 is the ASCII offset.

I'm not sure if this will ever be useful to anyone here but in case you want to write an encryption or decryption script these are pretty light.</char>