Advice Me
Advice Me

Reputation: 79

Convert from string to UInt32 - C#

I read UInt32 value as a string from XML file. And then I want to convert it to UInt32.

UInt32 res = Convert.ToUInt32("0x00B73004", 16);

But after converting the resulting value is: 12005380

Why it is so?

Upvotes: 1

Views: 1490

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

0x00B73004 is just hexadecimal notation of 12005380. Prefix "0x" is the most common notation to represents hexadecimal constants.

Since you asking why here a math side;

00B7300416 = 0 * 167 + 0 * 166 + B * 165 + 7 * 164 + 3 * 163 + 0 * 162 + 0 * 161 + 4 * 160

= 0 + 0 + 11 * 165 + 7 * 164 + 3 * 163 + 0 * 162 + 0 * 161 + 4 * 160

= 0 + 0 + 11534336 + 458752 + 12288 + 0 + 0 + 4

= 12005380

By the way Bhex = 11dec

You can save this hexadecimal notation in a numeric value like;

uint i = 0x00B73004;

Nothing wrong with that. You can see it's base 10 value on debugger.

enter image description here

Upvotes: 1

Martin Mulder
Martin Mulder

Reputation: 12954

As other answers suggest, the hexidecimal number B73004 equals the decimal number 12005380.

What you might forget is an UInt32 cannot hold any formatting. UInt32 is just a combination of 32 bits which represents a number; a value. How that number is displayed is entirely up to you. You can display it as an hexidecimal, binairy or decimal number. Example:

Console.WriteLine("{0} = {0:X}", res);

You can even tell Visual Studio to display the values in hexidecimal format with right-click on the Watch window and select 'Hexidecimal Display'.

This behavior is the same with float point number: It does not contain any information if it should be formatted with a dot or comma. That depends on the (current) culture. Also for the DateTime: It contains a date and time, without any formatting. The programmer can define how that date and time should be displayed (For example like: dd-MM-yyyy or yyyy-MM-dd, etc.)

Upvotes: 3

AKX
AKX

Reputation: 168967

It's working just as intended. 0xB73004 (with any number of leading zeroes) is 12005380 in decimal notation.

>>> hex(12005380)
'0xb73004'

Upvotes: 4

Related Questions