0

I've a List with either 1, 2 or 4 hex values saved as decimal values. I want to convert them into one decimal number.

Example:

List<Byte> values: 1 and 95 (= 0x01, 0x5F)

I want to convert the list into one decimal number: 0x015F = 351

How can I do that?

1
  • You need the output as 015F string or 351 in decimal? Commented Jul 18, 2014 at 9:03

3 Answers 3

4
var result = 0;
var i = 0;
foreach (var val in values) 
{
    result = (result << i) + (int)val;
    i += 8;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to generalize this solution. In case I don't know how many values I want to convert. For example: 0x00 0x20 0x00 0x30 0x10 0x24
It uses int (System.Int32), so will not work for a List<byte> with more than four entries. You can use long/ulong, or BigInteger, instead of int, for the result variable. Just change the first line to BigInteger result = 0;.
0

Modern, LINQ-based way (old-fashined C-programmers can turn in one's grave):

List<Byte> list = new List<byte>() { 0x01, 0x5F };
var output = list.Select(x => (int)x)
                 .Reverse()
                 .Aggregate((x, y) => (int)0x100 * y + (int)x);

Comments

0

With BitConverter class, you can do:

  var values = new List<byte> { 0x01, 0x5F, };

  byte[] arr = new byte[4];
  for (int i = 0; i < values.Count; ++i)
    arr[values.Count - 1 - i] = values[i];
  int result = BitConverter.ToInt32(arr, 0);

You fill the array arr backwards from the middle, as seen.

If the numbers can be greater (i.e. the List<> can be up to 8 bytes long), use ulong (never negative), for example:

  var values = new List<byte> { 0x01, 0x5F, };

  byte[] arr = new byte[8];
  for (int i = 0; i < values.Count; ++i)
    arr[values.Count - 1 - i] = values[i];
  ulong result = BitConverter.ToUInt64(arr, 0);

If the List<> can be arbitrarily long, use new BigInteger(arr) (requires csproj reference to System.Numerics.dll assembly).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.