Click here to Skip to main content
15,887,812 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
Hello everyone.

I would like help with a simple encode() and decode() function.

I am starting with a byte array, represented as hex, like the following

D4C7E156

and would like to encode this byte array into a BASE 10 representation, in little endian byte order.

If I put the above hex into a calc and convert it to decimal, I get the following

3569869142

Then I would like the decode function to take a string

string input = ("3569869142")

And decode it back into D4C7E156

I know this involves somekind of binary math routine, but I am at a loss.
I would be gratefull for any example code I could work with.

Thank you VERY much

Steve
Posted

This should work:

C#
static void Main ()
{
    string input = "D4C7E156";
    string output = Encode(input);
    Console.WriteLine(output);
    string originalInput = Decode(output);
    Console.WriteLine(originalInput);
    Console.WriteLine(input == originalInput);
}

private static string Decode(string output)
{
    Int64 result;
    Int64.TryParse(output, out result);
    return result.ToString("X");
}

private static string Encode(string input)
{
    Int64 result;
    Int64.TryParse(input, NumberStyles.HexNumber,
        CultureInfo.InvariantCulture, out result);
    return result.ToString();
}
 
Share this answer
 
That's not an encode or decode: all you are doing is changing the number base.
This has nothing to do with big-endian or little-endian: all you are doing is selecting to output a number in base 10 or 16.

Provided your decimal number does not exceed Int64.MaxInt, all you need to do is
C#
Int64 i = 0;
string dec = "3569869142";
string hex = "Input number conversion failed";
if (Int64.TryParse(dec, out i))
    {
    hex = i.ToString("X");
    }
Console.WriteLine(hex);
 
Share this answer
 
Comments
Sandeep Mewara 24-Feb-11 11:50am    
Comment from OP:
Provided your decimal number does not exceed Int64.MaxInt, all you need to do is"

This is the problem, I will need large strings of digits upto 50 decimal long.

I found an encode/decode function before and cant seem to find them, and they used bit math to do what I need.

Also, my bigest problem is inputting a text string of digits into the hex value to be converted.

Thank you

Steve

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