Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to transform ReadonlySpan<byte> to int?

Tags:

c#

.net

I have a file with a string "40070", I read it and transform it to a ReadonlySpan<byte> variable with 52, 48, 48, 55, 48 inside. This Span represents the number 40070. How can I cast/transform that ReadonlySpan<byte> back to an int?

Thanks

like image 250
Fritjof Berggren Avatar asked Dec 13 '25 11:12

Fritjof Berggren


2 Answers

ReadOnlySpan<byte> data = stackalloc byte[] { 52, 48, 48, 55, 48 };
// ^^^ or however you're getting your span; that part doesn't matter

if (System.Buffers.Text.Utf8Parser.TryParse(data, out int value, out int bytes))
{
    Console.WriteLine($"Parsed {bytes} bytes into value: {value}");
}
like image 78
Marc Gravell Avatar answered Dec 15 '25 00:12

Marc Gravell


You can read the initial data as chars, or convert the bytes into span of chars and use int.Parse/TryParse:

ReadOnlySpan<byte> span = new byte[] { 52, 48, 48, 55, 48 };
Span<char> chars = stackalloc char[span.Length];
Encoding.ASCII.GetChars(span, chars);
var result = int.Parse(chars);
Console.WriteLine(result); // prints "40070"
like image 27
Guru Stron Avatar answered Dec 14 '25 23:12

Guru Stron