Hex to int C# with VERY big numbers
Asked Answered
R

2

18

I have a 256 chars long string that contains a hex value:

EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679

I want to convert it to a string with numbers like this:

102721434037452409244947064576168505707480035762262934026941212181473785225928879178124028140134582697986427982801088884553965371786856967476796072433168989860379885762727214550528198941038582937788145880903882293999022181847665735412629158069472562567144696160522107094738216218810820997773451212693036210879

How can it be done with so big numbers?

Thanks in advance.

Rashida answered 27/6, 2011 at 20:3 Comment(2)
If the result should be decimal it would be 166089946137986168535368849184301740204613753693156360462575217560130904921953976324839782808018277000296027060873747803291797869684516494894741699267674246881622658654267131250470956587908385447044319923040838072975636163137212887824248575510341104029461758594855159174329892125993844566497176102668262139513.Bagwig
Unsigned, the decimal value is (negative) -13679367348245422237561669894600733157183944201074296810854863597601770883546986807868694514389259020824086818997645554366991899129900127598105731371799877496145234770598354025831263013337708672408763029044167695862514519205249993649664535030486133133888752089731139065617353812485871738338180226955961997703Edin
C
24

Use BigInteger. Specifically, you can use BigInteger.Parse to parse the hexadecimal representation to an instance of BigInteger (use NumberStyles.HexNumber), and then BigInteger.ToString to get the decimal representation.

var number = BigInteger.Parse(
    "EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679",
    NumberStyles.HexNumber
);
var s = number.ToString();
Cacuminal answered 27/6, 2011 at 20:7 Comment(1)
You need to prepend a 0 to the string, otherwise you will get a negative number if the first digit is between 8-F.Edin
T
3

Use the System.Numerics.BigInteger to store the number. To obtain it use BigInteger.Parse with a NumberFlags value where the AllowHexSpecifier is set. (Such as NumberFlags.HexNumber)

Trieste answered 27/6, 2011 at 20:6 Comment(2)
How can it convert a hex to a number and output it a a string?Rashida
A link to a documentation page is not terribly useful.Edin

© 2022 - 2024 — McMap. All rights reserved.