Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you wirte a code that can convert binary to hexadecimal just a simple code
Posted

I give you an example of 'manual computation' that your implementation could mimic, suppose you have the binary representation of a number, namely 10011.
It's value is 1 * 2^4 + 0 * 2^3 + 0 *2^2+ 1 * 2^1 + 1 * 2^0 = 16 + 2 + 1 = 19 (decimal).
You may obtain its octal representation by iteratively dividing it by power of 8, since 8^2 = 64 you may start with 8^1:
19 / 8^1 = 2, with reminder 3
now 3 / 8^0 = 3, hence the octal representation (of 19 decimal) is 23.
The same algo can be succesfully used for hex numbers, obtaining 13.
Excess-3 and Gray code are a bit more complex, you may look up their definition respectively here[^] and here[^] and then implement their algorithms.

Good luck.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Feb-12 18:35pm    
My 5.
--SA
I'd recommend you see if this CP article might meet all your needs: "Number base conversion class in C# by MarkGwilliam | 23 Dec 2006"[^], and then consider the information presented below.

However, the article linked to above does not deal with "exess 3 and to graycode."

There are no native representations for binary (base 2) or octal (base 8) integers in C#. The only possible integer "literals" are decimal and hexadecimal.

You can convert an integer which you intend to be octal or binary, to its equivalent integer value in bases 2, 8,10,16 by using the Convert.ToInt32(string value, int base) method which requires the first argument (the integer to be converted) to be in string form: the second argument specifies the base.

Try this:
int binInt1 = 11110;

octInt1 = 64;

// then execute this code:

int base8int = Convert.ToInt32(octInt1.ToString(), 8);

int base2int = Convert.ToInt32(binInt1.ToString(), 2);
And examine the results.

Of course once you have the actual integer value, converting to hexadecimal is trivial:
int base2AsHex = Convert.ToInt32(base2int.ToString(), 16);
But, you'll note that in all these examples you are "paying the price" for string conversion ... unless in your application you are already expressing octals and binaries as string.

Hence solutions, like the one cited at the top of this response, that try to speed-up conversions via code, and as found as in the answer by CPallini above, and, also, here:[^].

I find it strange that C# did not come with native built-in numeric base conversions that did not require string conversion or input.
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 6-Feb-12 18:35pm    
My 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900