Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex to int C# with VERY big numbers

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.

like image 237
Fredefl Avatar asked Jun 27 '11 20:06

Fredefl


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

Can I store a hex in an int?

Assigning the Hexadecimal number in a variable There is no special type of data type to store Hexadecimal values in C programming, Hexadecimal number is an integer value and you can store it in the integral type of data types (char, short or int).

What type is hex in C?

In C programming language, hexadecimal value is represented as 0x or 0X and to input hexadecimal value using scanf which has format specifiers like %x or %X.

Does atoi handle hex?

atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10.


2 Answers

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();
like image 51
jason Avatar answered Sep 29 '22 18:09

jason


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)

like image 20
Bas Avatar answered Sep 29 '22 19:09

Bas