BigInt from Javascript in C# equivalent - javascript

I have written a script in Javascript, which converts a string to BigInt:
BigInt("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088")
The result is: 28948022309972676171332135370609260321582865398090858033119816311589805691016
I need to find a C# equivalent to this function. I've tried:
Convert.ToInt64("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088") and BigInteger.Parse("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088",NumberStyles.Any)
But both throw the exception: the value could not be parsed.
Does anyone have an idea, what function would work to get the result from the string, like BigInt() in JS?

It should be converted BACK to a string format using the ToString()
Method and you need to pass the parameter in ToString of "R" which
tells it to output the BigInteger as itself.
This is from the documentation:
"In most cases, the ToString method supports 50 decimal digits of precision. That is, if the BigInteger value has more than 50 digits, only the 50 most significant digits are preserved in the output string; all other digits are replaced with zeros. However, BigInteger supports the "R" standard format specifier, which is intended to round-trip numeric values. The string returned by the ToString(String) method with the "R" format string preserves the whole BigInteger value and can then be parsed with the Parse or TryParse method to restore its original value without any loss of data."
You may want to try "R" instead of "N".
See this for more information and an example:
http://msdn.microsoft.com/en-us/library/dd268260.aspx

You need to remove the leading "0x" to parse hex.
private static BigInteger? ParseBigInteger(string input) {
if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
if (BigInteger.TryParse(input.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var bigInt)) {
return bigInt;
}
}
else if (BigInteger.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out var bigInt)) {
return bigInt;
}
return null;
}
//invocation
var bigInt = ParseBigInteger("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088");
// => result: 28948022309972676171332135370609260321582865398090858033119816311589805691016

It corresponds to the long (or Int64), a 64-bit integer
For ref: https://www.educative.io/edpresso/what-is-a-bigint-in-javascript

You need to remove 'x' character from the string and allow hex specifier then it will work:
BigInteger.Parse("0x40000000061c924300441104148028c80861190a0ca4088c144020c60c831088".Replace("x", string.Empty), NumberStyles.AllowHexSpecifier);

Related

why parseInt() in javascript converting "1abc" to 1?

I am trying to understand how parseInt() will work in javascript, my scenarios are
var x = parseInt("123");
console.log(x); // outputs 123
var x = parseInt("1abc");
console.log(x); // outputs 1
var x = parseInt("abc");
console.log(x); // outputs NaN
as of my observation parseInt() converts a string to integer(not really an integer of string like "12sv") when the string begins with number.
but in reality it should return NaN.
From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
"If the first character cannot be converted to a number, parseInt returns NaN."
From Mozilla's docs: "If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point."
So it will parse up to the first invalid character, drop the rest of the string, and return the int it managed to parse until then. If there's no valid characters it will return NaN.
parseInt()->it simply parse the provided value to its equivalent radix conversion,if specified without radix it converts to decimal equivalent.
for coercion purpose, we should avoid using parseInt,we can use Number() function instead.

How to convert a number 010 to a string "010"

While executing some random expressions in console, I just found that
010 + "" returning 8 (even 011,0100.. are returning results by considering octal number system)
What would I have to do if I want to convert a number 010 to a string "010"? Not only for 010 but for every similar numbers. I managed to find a kind of similar explanation for this here. But that is not explaining how to convert it into a exact string version.
In Javascript 010 is octal literal and converts to 8 in decimal literal. In fact, you should avoid it, as strict mode disallows to use it.
There is no way to distinguish between octal and decimal notation other than parsing function body string :)
Get a string first by invoking the toString() method with the base number which is 8 in this case
Number(010).toString(8); //outputs "10"
it works without wrapping in Number too,
010.toString(8); //outputs "10"
use this method to padd 0's if you know the length of original number
function pad(n,digits){return n<Math.pow(10, digits) ? '0'+n : n}
so
pad(Number(010).toString(8),3); //3 is the number of digits
Use the following code:
"0" + (010).toString(8) // "010"
"0" + (0111).toString(8) // "0111"
And a more general solution:
function toStringOctal(number) {
return "0" + number.toString(8);
}
toStringOctal(010) // return "010"
But notice that in strict mode octal notations 0<number> are not allowed.
var num = 10;
var string = "0" + num.toString();
console.log(string);//gives you "010"
As mentioned in the comments to this post, it won't convert 010 directly, but will build a string. Not the most elegant solution.
If you are looking to convert multiple similar numbers into strings, you could also build a simple function that will do the work when called:
function convertSomething(number) {
var string = "" + number;
return string
}
Then you can just call your conversion function whenever you need it.

Why does hex value is returned as a number in javascript

I tried the following code in a browser console.
var testingVar = 0xffff00;
When I access the variable it returned me the value 16776960 instead of the hexa value. Why does this happen? can't we store hexa value in the variable.
There's no such thing as a "hex value" in Javascript. There are strings and numbers.
0xffff00 is just an alternate syntax for specifying a number. By default the console will print numbers in decimal (base 10), which is why you see 16776960.
You can see a string representation of the number, using a different base with the toString method.
// hex
(0xffff00).toString(16) // "0xffff00"
// decimal
(0xffff00).toString(10) // "16776960"
// octal (for good measure)
(0xffff00).toString(10) // "77777400"
You can use hexadecimals in Javascript.
When you need to convert an octal or hexadecimal string to a number, use the function parseInt(str,base). Consider these examples, first you should define like below
var testingVar = '0xffff00';
And when you need you can call like below:
num = parseInt(testingVar, 16);

convert string generated from Number.toString to number

I use Number.toString method to convert numbers to string.
Number(100).toString(16);
Number(1000).toString(36);
How can I convert them back to the original numbers?
By using parseInt.
parseInt(Number(100).toString(16), 16);
parseInt(Number(1000).toString(36), 36);
Number("10") === 10
You can pass any string into Number and it will turn it into a number object. I prefer this method since if it contains any non-number characters, it will resolve to NaN which is what you want most of the time.
If you're parsing a string which begins with a number but may contain alpha characters afterwards, parseInt and parseFloat both will parse the leading numerics out - but you can forget about any numbers which may be mixed into the string elsewhere.

Javascript, why treated as octal

I'm passing as parameter an id to a javascript function, because it comes from UI, it's left zero padded. but it seems to have (maybe) "strange" behaviour?
console.log(0000020948); //20948
console.log(0000022115); //9293 which is 22115's octal
console.log(parseInt(0000022115, 10)); // 9293 which is 22115's octal
console.log(0000033959); //33959
console.log(20948); //20948
console.log(22115); //22115
console.log(33959); //33959
how can I make sure they are parsing to right numebr they are? (decimal)
EDIT:
just make it clearer:
those numbers come from the server and are zero padded strings. and I'm making a delete button for each one.
like:
function printDelButton(value){
console.log(typeof value); //output string
return '<img src="images/del.png">'
}
and
function printDelButton(value){
console.log(typeof value); //output numeric
console.log(value); //here output as octal .... :S
}
I tried :
console.log(parseInt(0000022115, 10)); // 9293 which is 22115's octal
and still parsing as Octal
If you receive your parameters as string objects, it should work to use
parseInt(string, 10)
to interpret strings as decimal, even if they are beginning with 0.
In your test, you pass the parseInt method a number, not a string, maybe that's why it doesn't return the expected result.
Try
parseInt('0000022115', 10)
instead of
parseInt(0000022115, 10)
that does return 221115 for me.
If you start it with a 0, it's interpreted as an Octal number.
See http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference#quickIDX2
Note the article's warning here:
You should never precede a number with a zero unless you are
specifically looking for an octal conversion!
Consider looking here for ideas on removing the leadings 0s:
Truncate leading zeros of a string in Javascript
Leading 0s indicate that the number is octal.
parseInt parses a string containing a number.
parseInt(0000022115, 10) passes a numeric literal. The literal is parsed in octal by the JS interpreter, so you're passing a raw numeric value to parseInt.
Unless you can intercept a string version of this number, you're out of luck.
That being said, if you can get a string version of your octal (calling toString() won't help), this will work:
parseInt(variable_string.replace(/^0+/, ''), 10);
Try
/^[0]*([1-9]\d)/.exec(numberFromUI)[0]
That should give you just the numbers stripping the zeros (if you have to support decimals, you'll need to edit to account for the '.', and of course ',' is fun too... and I really hope you don't have to handle all the crazy different ways Europeans write numbers! )
If number came from server as zero padded string then use +"0000022115"
console.log(+"0000022115")
if (021 < 019) console.log('Paradox');
JS treat zero padded numbers like octal only if they are valid octal - if not then it treat it as decimal. To not allow paradox 'use strict' mode
'use strict'
if (021 < 019) console.log('Paradox');

Categories