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...

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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?
@Stanislav: Well what did you want it to give? 10 isn't a digit. (This is why you really need to give clear requiremenst.)
well, got you right now... now know the mistake, thanks, was just a bit confused
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 :)
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.

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.