GameMaster Greatee
GameMaster Greatee

Reputation: 25

Conversion of Decimal to Hexadecimal

Let me describe the scenario first.

What I'm trying to do is convert a string to hex.

For example let's say a binary string comprising of 1s & 0s viz. 110011, pairing them as a group of 4 digits(appending two 0s for 8 digits here), converting each pair into hex separately and then joining the hex string result to obtain the output.

For octal, same as was for binary but here input octal string is split into groups of 3 digits

For ASCII, each digit's byte equivalent is converted to hex and stored.

Now the problem is what should I do for decimal string input?

-Should I consider using the same method as that for ASCII? -Or is there another way?

EDIT :-

I'm not just converting numbers, but converting an array of numbers.

Binary string - groups of 4 digits & then convert them to hex
Octal string - groups of 3 digits & then convert them to hex
ASCII string - byte equivalent for each character & then convert that to hex

So length isn't the issue. The issue is how to convert the decimal string(what sort of pairing/grouping should I use)

NOTE : I already know about converting octal, binary & decimal numbers to hex. This part is more about how to "divide the decimal string into groups" so as to convert each decimal group into hex separately and then joining the resultant hex.

Upvotes: 0

Views: 13372

Answers (2)

Abion47
Abion47

Reputation: 24606

There's no need to reinvent the wheel here.

string input = "123456";
string outputHex = int.Parse(input).ToString("X");

// output = "1E240"

Or even better:

string outputHex = Convert.ToString(int.Parse(input), 16);

This method lets you do other number systems as well:

string outputOct = Convert.ToString(int.Parse(input), 8);
string outputBin = Convert.ToString(int.Parse(input), 2);

Upvotes: 6

Bishal
Bishal

Reputation: 837

Easiest way to achieve it would be to regard the digits as ASCII characters(0-9 have ASCII values 48-57) and convert it to Hex like you are already doing.

If you want to do it in another way, you would need to introduce new logic to your program. It depends upon your personal preference.

Upvotes: 0

Related Questions