gpt4 book ai didi

javascript - 在 Javascript 中添加或减去 64 位整数

转载 作者:行者123 更新时间:2023-11-29 10:48:42 26 4
gpt4 key购买 nike

有没有简单的方法(希望是一个小函数,而不是库)在 JavaScript 中对 64 位整数进行加减?

示例 64 位整数:291270990346989568

背景:我正在使用具有 64 位推文 ID 的 Twitter API。我想从这些 ID 中添加或减去一个以操纵我从 Twitter 返回的结果。

最佳答案

以下代码执行您所描述的内容。

Splitting, adding or subtracting, then re-joining...

此代码同时具有递增和递减函数,以及具有一些边缘情况的测试函数。在拆分数字字符串并对它们进行数学运算时,您需要考虑“前导零”会发生什么情况,因此有一个填充函数。

谢谢贾斯汀提供 JSFiddle with this solution .

/*
* Prepend zeros to expand a given string to given length
*
* @var {String} numStr Number
* @var {Number} len Length to pad out to
*
* @returns {String}
*/
function pad0 (numStr,len) {
while (numStr.length < len) {
numStr = "0" + numStr;
}
return numStr
}

/*
* Decrement the given (64 bit) integer.
*
* @var {String} int64 Postive non-zero integer, as a string
*
* @returns {String}
*/
function decrInt64 (int64) {
var result = "";
var midpt = Math.floor(int64.length/2);
var upper = int64.substring(0,midpt);
var lower = int64.substring(midpt);
var upperVal = new Number(upper);
var lowerVal = new Number(lower);

if (lowerVal == 0) {
if (upperVal == 0) {
// We don't support negative numbers
result = "*ERROR*"
}
else {
// borrow 1
result = pad0((--upperVal).toString(),upper.length) +
(new Number("1"+lower) - 1).toString();
}
}
else {
var newLower = (lowerVal - 1).toString();
result = upper + pad0(newLower,lower.length);
}
alert(result);
}

/*
* Increment the given (64 bit) integer.
*
* @var {String} int64 Postive, as a string
*
* @returns {String}
*/
function incrInt64 (int64) {
var result = "";
var midpt = Math.floor(int64.length/2);
var upper = int64.substring(0,midpt);
var lower = int64.substring(midpt);
var upperVal = new Number(upper);
var lowerVal = new Number(lower);

var newLower = (++lowerVal).toString();
// Did we overflow?
if (lower.length < newLower.length) {
// Yes, carry the 1
result = (++upperVal).toString() + newLower.substring(1);
}
else {
result = upper + pad0(newLower,lower.length);
}
alert(result);
}

// Test function
window.displaymessage= function ()
{
decrInt64("291270990046989568");
incrInt64("291270990046989568");
decrInt64("000000000000000000");
incrInt64("000000000000000000");
decrInt64("000000001000000000");
incrInt64("000000001000000000");
decrInt64("099999999999999999");
incrInt64("099999999999999999");
decrInt64("999999999999999999");
incrInt64("999999999999999999");
}

关于javascript - 在 Javascript 中添加或减去 64 位整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14347441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com