当前位置:网站首页>How does JS use hexadecimal to save 100-bit state
How does JS use hexadecimal to save 100-bit state
2022-08-08 03:06:00 【light night】
Now the development encounters a requirement,需要保存100个状态,状态只有
0和1两种状态,If using string save100个0和1,Then it will be very long, Then I thought of turning it into16进制
思考
但是在
JS里最大的安全整数Number.MAX_SAFE_INTEGERThe maximum can only be9007199254740991这么大.
// Convert the largest safe integer to 16进制
(Number.MAX_SAFE_INTEGER).toString(16)
// 0x1FFFFFFFFFFFFF
结果发现只有13个
F,一个F可以表示4位(1111),即13*4=52Normally only save52位
// 转成二进制
parseInt('0xFFFFFFFFFFFFF').toString(2)
// 1111111111111111111111111111111111111111111111111111
// 计算下长度
parseInt('0xFFFFFFFFFFFFF').toString(2).length
// 52
If so, add one more
F呢?14个F(Found that there seems to be no problem?!真的没问题吗??)
parseInt('0xFFFFFFFFFFFFFF') // 72057594037927940
Now do the down conversion to binary and calculate the down length
// 转成二进制
parseInt('0xFFFFFFFFFFFFFF').toString(2)
// '100000000000000000000000000000000000000000000000000000000'
// 计算下长度
parseInt('0xFFFFFFFFFFFFFF').toString(2).length
// 57
It can be seen that there is a problem,The converted binary is incorrect,wrong length.
那么没办法了,Only within safe limits52位可以用(It is also necessary to pay attention to safety when writing code,不然出错了,I don't know why)
然后就想到了,There is no need to use two
52 * 2 = 104个了,Then it suffices
实现
保存数据的格式,我使用的是
.进行数据分割,即整数.小数的数据格式.
Then it can be dealt with separately,I'm using the integer part first,即[0-49].[50-99]这种方式保存
Later found a problem not to use bitwise operations directly,Because bit operations are only supported32位以内的,这样就麻烦了
I did it by converting hex to binary string,Then convert to hexadecimal,This does not involve bit operations
Regarding the preservation of the location,Since the array is on the left side is0位,We change directly0位,Then the initial data will be very large,所以我们要反过来,Change from the highest bit of the array.
// 第一位为1
1 '1000' => 8 '0001' => 1
// 第二位为1
3 '1100' => 8 '0011' => 3
// 第三位为1
7 '1110' => 8 '0111' => 7
We use the latter save method,In this way, the data will be changed from small to large after conversion,Also in line with our habits.
Basic version conversion
Now this is only supported50位以内的
/** * Binary increment operation * @param {String} data 十六进制 * @param {Number} pos 位 * @return {String} Calculated hexadecimal value */
function addBinaryVal(data, pos) {
// 超过50Bits are not converted
if (pos >= 50){
return data;
}
// Convert hexadecimal to binary first,Fill in the front 0,Then split into arrays,Then replace the state at the specified location,Finally, convert to hexadecimal
let binaryData = parseInt(data, 16).toString(2).padStart(50, '0').split('');
// Change the specified location
binaryData[49-pos] = '1';
return '0x' + parseInt(binaryData.join(''), 2).toString(16)
}
Enhanced conversion
可以支持100位或者150位甚至更高,我这里只是100位,It can be expanded as needed
Encapsulates a method to make state changes
/** * Sets the hexadecimal string specified position value to 1 * Calculated separately for the two hex strings,然后再还原 * @param {String} data 数据 Two hexadecimal strings * @param {Number} pos 位置 范围限制[0,99] * @return {String} 改变后的字符串 */
function replaceBinaryValByPos(data, pos){
if (pos > 100 || pos < 0){
logger.error("getBinaryValByPos data: %j pos: %j is invalid");
return data;
}
let tempData = data.split('.');
if(pos < 50){
tempData[0] = addBinaryVal(tempData[0], pos);
}else{
tempData[1] = addBinaryVal(tempData[1], pos-50);
}
return tempData.join('.');
}
let val = '0xa.0xa' // '1010.1010'
val = replaceBinaryValByPos(val, 0) // '1011.1010'
console.log(val) // '0xb.0xa'
val = replaceBinaryValByPos(val, 50) // '1010.1011'
console.log(val) // '0xa.0xb'
Get the state of the corresponding bit
Encapsulates a method fixed method to obtain the state of the data
/** * The hexadecimal string specifies the status of the location * Convert the largest safe integer to binary 可以有53位 只取用50位,Two strings can be there100位 * @param {String} data 数据 Two hexadecimal strings * @param {Number}pos 位置 范围限制[0,99] * @return {boolean} 状态 [true,false] */
function getBinaryValByPos(data, pos){
if (pos > 100 || pos < 0){
logger.error("getBinaryValByPos data: %j pos: %j is invalid");
// Invalid status returnedtrue Indicates that it has taken effect,Prevent repeated operations due to ineffectiveness
return true;
}
if(pos < 50){
let val = parseInt(data.split('.')[0], 16).toString(2).padStart(50, '0');
return val.charAt((50-1) - pos) === '1';
}else{
let val = parseInt(data.split('.')[1] || '0x0', 16).toString(2).padStart(50, '0');
return val.charAt((100-1) - pos) === '1';
}
}
let val = '0xa.0xb' // ==> '1010.1011'
console.log(getBinaryValByPos(val,0)) // false
console.log(getBinaryValByPos(val,1)) // true
console.log(getBinaryValByPos(val,2)) // false
Convert hexadecimal data to binary string
Here is the conversion of hexadecimal data to binary string,However, the data state is saved from left to right
这样方便使用
/** * Get the binary format string * 反向组合 从左往右算 * @param data 数据 Two hexadecimal strings * @return {string} 二进制字符串 */
function getBinaryStr(data) {
let tempData = data.split('.');
let len = 50;
let strArr = [];
strArr[0] = parseInt(tempData[0], 16).toString(2).padStart(len, '0').split('').reverse().join('');
strArr[1] = parseInt(tempData[1], 16).toString(2).padStart(len, '0').split('').reverse().join('');
return strArr.join('');
}
let val = '0xa.0xb' // 1010 1011 翻转=> 01011101
val = getBinaryStr(val);
console.log(val) // '0101000...0001101000...000' =>总长度100
结束
Here is just the way I came up with it,如果有更好的方法,可以一起探讨交流
I'll update if I find something better,加油!
边栏推荐
- Several daily LeetCode exercises
- 1.9 and orderly array insert PTA problem sets
- STM32F103C8/BT6 USART1 DMA发送失败
- The difference between orElse and orElseGet in Optional
- 找素数问题
- 意识的概念框架:我们的意识从注意图式产生?
- 音视频基础
- KDD'22 | CausalMTA: 基于因果推断的无偏广告多触点归因技术
- The fourth chapter of the original CSharp c # common years is hard to know the humanistic one after another
- egg-session 将数据存储到redis
猜你喜欢

Audio and Video Basics
![[Actual combat explanation] Implementation of data blood relationship](/img/ed/d6010a3890ce482f19ee9edabfd4fe.png)
[Actual combat explanation] Implementation of data blood relationship

LeetCode二叉树系列——257二叉树的所有路径

Negative Number Storage and Type Conversion in Program

音视频基础

DolpinScheduler

The ORACLE database connection exception after restart

The futures company how to validate the normality of opening an account

QML ListView详解

巧记硬链接与软链接
随机推荐
121. Best Time to Buy and Sell Stock买卖股票的最佳时机
Online futures account opening is becoming more and more popular
海外元宇宙媒体宣发一定要关注到宣传的整体性
SQL 2016 如何跟踪是哪个存储或语句导致记录表中记录被修改了
产品经理必备的19类工具网站
LED驱动程序进一步优化-分层-分离
基于图像二维熵的视频信号丢失检测(Signal Loss Detection)
系统滴答及Systick定时器
Lecture 84th Biweekly
杭电多校-Map-(模拟退火)
保姆级教程!Golang微服务简洁架构实战
KDD'22 | CausalMTA: Unbiased Advertising Multi-Touch Attribution Technology Based on Causal Inference
PTA Exercise 1.8 Binary Search
PC Museum (Fanwai 01)-Chenghuiwan, junior high school students develop a large-scale navigation game with physical scales
Embedded Interview Questions
Win11右键恢复经典win10最简单方法(基本0操作)
egg-validate-自定义校验方法报错语言(报错中文提示)
Detailed QML ListView
egg-session 将数据存储到redis
121. The Best Time to Buy and Sell Stock, the Best opportunity to Buy and Sell stocks