0

Let's say I have array of bytes

byte[] byteArr = new byte[] { 1, 2, 3, 4, 5 };

I want to convert this array to get regular numeric variable of uint, so result will be

uint result = 12345;

So far all the example I've seen were with bytes, byte I don't need bytes, but numeric value.

Thanks...

inside
  • 3,047
  • 10
  • 49
  • 75

1 Answers1

2

It sounds like you want something like:

uint result = 0;
foreach (var digit in array)
{
    result = result * 10 + digit;
}

Or more fancily, using LINQ:

uint result = array.Aggregate((uint) 0, (curr, digit) => curr * 10 + digit);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hey John, very important question, why is this works only for numbers until 10? If I will convert it from byte array 1, 2, 3, 4, 5, 6, 7, 8, 9 it will give me result 123456789, but if I will convert it from byte array 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 it will give me 1234567900 please need to know how to fix it? – inside Apr 11 '13 at 13:50
  • 1
    @Stanislav: Well what did you *want* it to give? 10 isn't a digit. (This is why you really need to give clear requiremenst.) – Jon Skeet Apr 11 '13 at 13:51
  • well, got you right now... now know the mistake, thanks, was just a bit confused – inside Apr 11 '13 at 13:54
  • but if you have quick answer on how to parse it if there is number higher than 9 and you can share would be great :) – inside Apr 11 '13 at 13:55
  • A solution requires a problem. Maybe we should just ignore any values over 9. Maybe we should throw an exception. Maybe we should change it to a random number. Without requirements, it's impossible to suggest an implementation. – Jon Skeet Apr 11 '13 at 13:58