Roka545
Roka545

Reputation: 3626

Parsing a hexadecimal string in C#

I have the following hexadecimal string (little endian form):

ffffffffffff0800272bfcf608004500

and I need to decode it into several fields. I know the first field is a marker for 'version' and it is a uint16. I have a Python script that decodes the above string and it tells me that 'version' is 258. Now I'm trying to decode it in C#.

From my understanding, a uint16 is 2 bytes, so ffff (4 bits per character) should give me the 'version' marker correct? I use

UInt16.Parse("ffff");

but I get the error:

"Input string was not in a correct format."

What exactly am I doing wrong?

Upvotes: 2

Views: 2488

Answers (1)

fhcimolin
fhcimolin

Reputation: 614

You could either do:

int result = int.Parse("ffff", System.Globalization.NumberStyles.HexNumber);

or

int result = Convert.ToInt16("ffff", 16);

Note that the second argument is the provider in the first case, and in the second it's the base.

Upvotes: 4

Related Questions