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
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
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}");
}
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"