How parseInt gets its value

parseInt('bcedfg',16) 

Basics for this code I get 773855 in JavaScript,

I am looking at a conversion table and not sure how to get this value of "773855"

My question is how parseint will come out with this value of "773855" because I wanted to translate this tiny code into aC # code and that any similar way in C # allows me to get that value of "773855"

+4
source share
2 answers

Use Convert.ToInt32 :

 Convert.ToInt32(theString, 16) 

It uses this overload:

 public static int ToInt32(string value, int fromBase) 

Note that you will get a FormatException due to g in the line:

FormatException
the value contains a character that is not a valid digit in the base specified by the fromBase function . An exception message indicates that there are no digits to convert if the first character in the value is invalid; otherwise, the message indicates that the value contains invalid trailing characters.

MSDN

You are not getting an error in javascript since js tends to “forgive” too many errors, this is one of these examples.

+6
source

bcedfg interpreted as hex (base: 16 ). However, the hexadecimal scale collapses after f , so in javascript, g and everything after it is deleted before conversion. With that said here, how the conversion works:

 decValueOfCharPosition = decValueOfChar * base ^ posFromTheRight 

So:

 b = 11 * 16^4 = 11 * 65536 = 720896 c = 12 * 16^3 = 12 * 4096 = 49152 d = 13 * 16^2 = 13 * 256 = 3328 e = 14 * 16^1 = 14 * 16 = 224 f = 15 * 16^0 = 15 * 1 = 15 

Once you recognize the decimal value for each character position, just add them together to get the converted decimal value:

 b(720896) + c(49152) + d(3328) + e(224) + f(15) = 773855 

C, and this offspring is not so soft when it comes to typing. Instead of deleting the first invalid character and any characters that may follow it, C throws a Format Exception . To get around this, in order to get javascript functionality, you must first remove the invalid character and its subsequent ones, then you can use:

 Convert.ToInt32(input, base) 

I did not include a way to remove invalid characters due to the fact that there are several ways to make as such, and my sub-sub-C knowledge

+10
source

Source: https://habr.com/ru/post/1441079/


All Articles