Convert a long String to to a big int in javascript - javascript

im doing some stuff in javaScript and therefore need to convert a Text String to Decimal .
The php code that i used was:
function to_number($data)
{
$base = "256";
$radix = "1";
$result = "0";
for($i = strlen($data) - 1; $i >= 0; $i--)
{
$digit = ord($data{$i});
$part_res = bcmul($digit, $radix);
$result = bcadd($result, $part_res);
$radix = bcmul($radix, $base);
}
return $result;
}
since i need to do it in Javascript i tried to convert The String into Hex and then into a Decimal String :
/// String into Hex
function toHex(str) {
var hex = '';
var i = 0;
while(str.length > i) {
hex += ''+str.charCodeAt(i).toString(16);
i++;
}
return hex;
}
//// Hex into Dec
function h2d(s) {
function add(x, y) {
var c = 0, r = [];
var x = x.split('').map(Number);
var y = y.split('').map(Number);
while(x.length || y.length) {
var s = (x.pop() || 0) + (y.pop() || 0) + c;
r.unshift(s < 10 ? s : s - 10);
c = s < 10 ? 0 : 1;
}
if(c) r.unshift(c);
return r.join('');
}
var dec = '0';
s.split('').forEach(function(chr) {
var n = parseInt(chr, 16);
for(var t = 8; t; t >>= 1) {
dec = add(dec, dec);
if(n & t) dec = add(dec, '1');
}
});
return dec;
}
Everything works fine and both php and javascript code returns exact same result when i feed them with a regular String like :
thisisasimplestring
but when feeding an input like this:
�ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ�!µ?ŲÀ]).-PSH9Ó·ÂÞ
or even this:
�ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ�yohoo
the result of javascript code will be diffrent from php.
i need a result same as php.
Any idea? im looking for help

although i solved the problem with another solution, but for the refrence its because of the way that javascript handle the characters (characters like those i need) , so
str.charCodeAt(i)
won't return a correct code point for that character.
i suggest reading this article :
http://mathiasbynens.be/notes/javascript-unicode

Related

Javascript Integer Array Error

I'm making a function that takes in user input and must display it as 7 characters i.e. if 42.54 was entered it would display 0004254. My issue is that I'm taking an integer and applying it to an array causing an undefined error when applying the 0's
function BackDataDefaultInput() {
// Balance
var count;
var newNum = "";
var balanceText = document.getElementById('balanceNumBox').value;
count = balanceText.length;
while (count > 0 && count < 7) {
newNum += '0';
count++
}
var formattedBalance = parseInt(balanceText, 10) * 100;
for (var i = 0; i < balanceText.length; i++) {
formattedBalance[i] = new Array();
// Error here showing as undefined for formattedBalance[i]
newNum += formattedBalance[i];
}
This code worked before I had to multiply it by 100 to get the right format. as I was just appending two strings. Can somebody help me think of a solution?
Primitives (like numbers) are immutable; if you have
var formattedBalance = parseInt(balanceText, 10) * 100;
you can't proceed to reassign index properties like
formattedBalance[i] = new Array();
It would probably be easier to remove the (possible) period with a regex and use padStart rather than mess with arrays:
function BackDataDefaultInput() {
const balanceText = '42.54'; // document.getElementById('balanceNumBox').value;
console.log(
balanceText
.replace(/\./g, '')
.padStart(7, '0')
);
}
BackDataDefaultInput();
Try to use following function.
var balanceText = "42.54"; //document.getElementById('balanceNumBox').value;
var formattedBalance = balanceText * 100;
function formatInteger(str, max) {
str = str.toString();
return str.length < max ? formatInteger("0" + str, max) : str;
}
console.log(formatInteger(formattedBalance, 7));
Answer to my question in case it helps anyone that comes across this page:
function BackDataDefaultInput() {
var balanceText = document.getElementById('balanceNumBox').value;
var balance = parseFloat(balanceText) * 100;
balanceText = String(balance);
while (balanceText.length > 0 && balanceText.length < 7) {
balanceText = '0' + balanceText;
}
}

need help converting C# code to javascript / reversing a function output

I'm working on a function that converts a number to string and string to a number.
the original c# code
public static string unhash(Int64 hash)
{
string originalString = "";
Int64 mod = 37;
string letters = "acdegilmnoprstuw";
while (hash != 7)
{
Int64 index = hash % mod;
originalString = letters[(Int32) index] + originalString; // need help converting this line to javascript
hash = (hash - index) / mod;
}
return originalString;
}
the javascript code
this is working correctly as it convert string into hash that I want
function hash (s) {
var h = 7;
var letters = "acdegilmnoprstuw";
for (i = 0; i < s.length; i++) {
h = (h * 37 + letters.indexOf(s[i]))
}
return h;
}
the code to reverse the process of hash to string, it not working correctly
function unhash (hash) {
var originalString = "";
var mod = 37;
var letters = "acdegilmnoprstuw";
while( hash != 7) {
var index = hash % mod;
originalString = letters[(Int32Array)index] + originalString; // I'm not sure what the javascript version of int32
hash = (hash - index) / mod;
}
}
alert(hash("leepadg")); // this is the correct output 680131659347
alert(unhash( 680131659347)); //output supposed to be leepadg but returning undefined

Get Number of Decimal Places with Javascript

How would I calculate the number of decimal places (not digits) of a real number with Javascript?
function countDecimals(number) {
}
For example, given 245.395, it should return 3.
Like this:
var val = 37.435345;
var countDecimals = function(value) {
let text = value.toString()
// verify if number 0.000005 is represented as "5e-6"
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-');
let deg = parseInt(trail, 10);
return deg;
}
// count decimals for number in representation like "0.123456"
if (Math.floor(value) !== value) {
return value.toString().split(".")[1].length || 0;
}
return 0;
}
countDecimals(val);
The main idea is to convert a number to string and get the index of "."
var x = 13.251256;
var text = x.toString();
var index = text.indexOf(".");
alert(text.length - index - 1);
Here is a method that does not rely on converting anything to string:
function getDecimalPlaces(x,watchdog)
{
x = Math.abs(x);
watchdog = watchdog || 20;
var i = 0;
while (x % 1 > 0 && i < watchdog)
{
i++;
x = x*10;
}
return i;
}
Note that the count will not go beyond watchdog value (defaults to 20).
I tried some of the solutions in this thread but I have decided to build on them as I encountered some limitations. The version below can handle: string, double and whole integer input, it also ignores any insignificant zeros as was required for my application. Therefore 0.010000 would be counted as 2 decimal places. This is limited to 15 decimal places.
function countDecimals(decimal)
{
var num = parseFloat(decimal); // First convert to number to check if whole
if(Number.isInteger(num) === true)
{
return 0;
}
var text = num.toString(); // Convert back to string and check for "1e-8" numbers
if(text.indexOf('e-') > -1)
{
var [base, trail] = text.split('e-');
var deg = parseInt(trail, 10);
return deg;
}
else
{
var index = text.indexOf(".");
return text.length - index - 1; // Otherwise use simple string function to count
}
}
You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:
function countPlaces(num) {
var sep = String(23.32).match(/\D/)[0];
var b = String(num).split(sep);
return b[1]? b[1].length : 0;
}
console.log(countPlaces(2.343)); // 3
console.log(countPlaces(2.3)); // 1
console.log(countPlaces(343.0)); // 0
console.log(countPlaces(343)); // 0
Based on Gosha_Fighten's solution, for compatibility with integers:
function countPlaces(num) {
var text = num.toString();
var index = text.indexOf(".");
return index == -1 ? 0 : (text.length - index - 1);
}
based on LePatay's solution, also take care of the Scientific notation (ex: 3.7e-7) and with es6 syntax:
function countDecimals(num) {
let text = num.toString()
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-')
let elen = parseInt(trail, 10)
let idx = base.indexOf(".")
return idx == -1 ? 0 + elen : (base.length - idx - 1) + elen
}
let index = text.indexOf(".")
return index == -1 ? 0 : (text.length - index - 1)
}
var value = 888;
var valueLength = value.toString().length;

JavaScript encoding with Special characters

I wanted to write a method to escape special chars like 'ä' to their responding Unicode (e.g. \u00e4).
For some reason JS finds it amusing to not even save the 'ä' internally but use 'üÜ' or some other garble, so when I convert it spits out '\u00c3\u00b6\u00c3\u002013' because it converts these chars instead of 'ä'.
I have tried setting the HTML file's encoding to utf-8 and tried loading the scripts with charset="UTF-8" to no avail. The code doesn't really do anything special but here it is:
String.prototype.replaceWithUtf8 = function() {
var str_newString = '';
var str_procString = this;
for (var i = 0; i < str_procString.length; i++) {
if (str_procString.charCodeAt(i) > 126) {
var hex_uniCode = '\\u00' + str_procString.charCodeAt(i).toString(16);
console.log(hex_uniCode + " (" + str_procString.charAt(i) + ")");
str_newString += hex_uniCode;
} else {
str_newString += str_procString.charAt(i);
}
}
return str_newString;
}
var str_item = "Lärm, Lichter, Lücken, Löcher."
console.log(str_item); // Lärm, Lichter, Lücken, Löcher.
console.log(str_item.replaceWithUtf8()); //L\u00c3\u00a4rm, Lichter, L\u00c3\u00bccken, L\u00c3\u00b6cher.
I have no idea how or why but I just restarted the server again and now it's displaying correctly. To follow up; here's the code for everyone who's interested:
String.prototype.replaceWithUtf8 = function() {
var str_newString = '';
var str_procString = this;
var arr_replace = new Array('/', '"');
var arr_replaceWith = new Array('\\/', '\\"');
for (var i = 0; i < str_procString.length; i++) {
var int_charCode = str_procString.charCodeAt(i);
var cha_charAt = str_procString.charAt(i);
var int_chrIndex = arr_replace.indexOf(cha_charAt);
if (int_chrIndex > -1) {
console.log(arr_replaceWith[int_chrIndex]);
str_newString += arr_replaceWith[int_chrIndex];
} else {
if (int_charCode > 126 && int_charCode < 65536) {
var hex_uniCode = '\\u' + ("000" + int_charCode.toString(16)).substr(-4);
console.log(hex_uniCode + " (" + cha_charAt + ")");
str_newString += hex_uniCode;
} else {
str_newString += cha_charAt;
}
}
}
return str_newString;
}
Use '\\u' + ('000' + str_procString.charCodeAt(i).toString(16) ).stubstr(-4); instead to get the right escape sequences - yours do always start with 00. Also, instead of a for-loop processing your string, .replace() might be faster.
On your question:
console.log("Lärm, Lichter, Lücken, Löcher."); // Lärm, Lichter, Lücken, Löcher.
does not sound as you really sent the file with the right encoding. Might be a server problem, too, if it is correctly saved already.
String.prototype.replaceWithUtf8 = function() {
function r(r) {
for (var t, n, e = "", i = 0; !isNaN(t = r.charCodeAt(i++)); ) n = t.toString(16),
e += 256 > t ? "\\x" + (t > 15 ? "" :"0") + n :"\\u" + ("0000" + n).slice(-4);
return e;
}
var a, c, o, u, s, e = "", i = this, t = [ "/", '"' ], n = [ "\\/", '\\"' ];
for (a = 0; a < i.length; a++) c = i.charCodeAt(a), o = i.charAt(a), u = t.indexOf(o),
u > -1 ? e += n[u] :c > 126 && 65536 > c ? (s = r(o), e += s) :e += o;
return e;
};
prompt("Your escaped string:","Lärm, Lichter, Lücken, Löcher.".replaceWithUtf8());
alert("L\xe4rm, Lichter, L\xfccken, L\xf6cher.");
Unicode encoding only makes every character 6 digits. But for characters above 127 to 256, we can actually make these hexdecimal with less bytes (4 digits per character).

Formatting currency with commas in Javascript for Adobe Acrobat

When adding Javascript to a PDF, is it possible for me to print a float so that it looks like this: $50,0000?
I don't care about internationalization.
I can use util.printf, but it won't put the commas in.
Did you mean to do it by javascript. Does this help you.
formatNumber
function formatNumber( num ) {
var decimalPart = '';
num = num.toString();
if ( num.indexOf( '.' ) != -1 ) {
decimalPart = '.'+ num.split( '.' )[1];
num = parseInt(num.split( '.' )[0]);
}
var array = num.toString().split( '' );
var index = -3;
while ( array.length + index > 0 ) {
array.splice( index, 0, ',' );
index -= 4;
}
return array.join( '' ) + decimalPart;
}
A simple add commas function is:
function addCommas(num) {
var num = String(num);
var bits, num0, s, f, len, sign = '', result = [];
if (/^[+-]/.test(num)) {
sign = num.substring(0,1);
num = num.substring(1);
}
bits = String(num).split('.');
num0 = bits[0];
s = 0, f = num0.length % 3 ;
len = num0.length;
if (num0.length > 3) {
while (f <= len) {
f && result.push(num0.substring(s, f));
s = f;
f += 3;
}
result = result.join(',') + (bits[1]? '.' + bits[1] : '');
}
return sign + (s? result : num);
}
There are probably a million similar functions, try Google.
Edit
Fixed issue where length > 6 and num % 3 == 0
Added support for -ve numbers
A little late but...
printf will add commas.
util.printf("%,0.0f", numberValue);
See JavaScript™ for Acrobat® API Reference for more...
This solution will also work for negative numbers as well.
function addCommas( num ) {
var parts = num.toString(10).split(".");
parts[0] = parts[0].reverse().replace(/(\d{3})/g, "$1,").reverse();
return parts.join(".");
}
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
Fiddle here

Categories

Resources