从JavaScript中获得两个字节的最佳方法?
-
04-10-2019 - |
题
我正在用JavaScript中解析一个二进制文件,该文件正在存储每个字节的两种信息,一个每本bble。这些值当然是0-16和0-16。
在文件格式的所有其他部分中,每个字节代表一个信息,因此我一直在使用以下内容来成功获取所需的数字值:
var num = str.charCodeAt(0) & 0xFF;
但是我坚持不懈地试图弄清楚如何获得第一个nibble的0-16值,而对于我的单个字节字符“ str”而言,第二个nibble也是如此。
感谢任何帮助。
解决方案
var num = str.charCodeAt(0) & 0xFF;
var nibble1 = num & 0xF;
var nibble2 = num >> 4;
其他提示
你可以做:
var num = str.charCodeAt(0);
var lower_nibble = (num & 0xF0) >> 4;
var higher_nibble = num & 0x0F;
它是如何工作的?
让我们假设位表示 num
是 abcdwxyz
我们想提取 abcd
较高的鼻子和 wxyz
较低的鼻子。
为了提取下部的鼻子,我们只是通过位和数字用 0x0F
:
a b c d w x y z
&
0 0 0 0 1 1 1 1
---------------
0 0 0 0 w x y z = lower nibble.
为了提取较高的刺 0xF0
作为:
a b c d w x y z
&
1 1 1 1 0 0 0 0
---------------
a b c d 0 0 0 0
然后,我们右手向右移动结果4次,以摆脱尾随的零。
右右移动可变1次会使最右边的位使其松动,并使左侧位最零:
a b c d w x y z
>> 1
----------------
0 a b c d w x y
类似的位右移动 2
时间将引入结果:
a b c d w x y z
>> 2
----------------
0 0 a b c d w x
和位右班 4
时间给出:
a b c d w x y z
>> 4
----------------
0 0 0 0 a b c d
从清楚地看出的结果是,字节的较高(abcd
).
由于我很喜欢这个,所以我想添加一些我刚写的东西可能很有用。也许其他人也会发现它也有用。
原型:
Number.prototype.fromCharCode = function () {return String.fromCharCode(this); };
String.prototype.byte = function (val){ var a = new Array();
for(var i=(val||0),n=val===0?0:this.length-1; i<=n; i++){
a.push(this.charCodeAt(i) & 0xFF);
}
return a;
};
String.prototype.HiNibble = function (val){
var b = this.byte(val);
var a = new Array();
for(var i=0,n=b.length-1; i<=n; i++){a.push(b[i] >> 4);}
return a;
};
String.prototype.LoNibble = function (val){
var b = this.byte(val);
var a = new Array();
for(var i=0,n=b.length-1; i<=n; i++){a.push(b[i] & 0xF);}
return a;
};
示例调用:
var str = new String("aB");
console.log(str.byte()); // [ 97, 66 ]
console.log(str.HiNibble()); // [ 6, 4 ]
console.log(str.LoNibble()); // [ 1, 2 ]
console.log(str.byte(0)); // [ 97 ]
console.log(str.HiNibble(0)); // [ 6 ]
console.log(str.LoNibble(0)); // [ 1 ]
var bar = "c";
console.log(bar.byte()); // [ 99 ]
console.log(bar.HiNibble()); // [ 6 ]
console.log(bar.LoNibble()); // [ 3 ]
var foobar = (65).fromCharCode(); // from an integer (foobar=="A")
console.log(foobar.byte()); // [ 65 ]
console.log(foobar.HiNibble()); // [ 4 ]
console.log(foobar.LoNibble()); // [ 1 ]
只是添加了可能的帮助,但在上述未使用:
/* Useful function that I modified
Originally from: http://www.navioo.com/javascript/dhtml/Ascii_to_Hex_and_Hex_to_Ascii_in_JavaScript_1158.html
*/
function AscHex(x,alg){
hex = "0123456789ABCDEF";
someAscii = ' !"#$%&\''
+ '()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\'
+ ']^_`abcdefghijklmnopqrstuvwxyz{|}';
r = "";
if(alg=="A2H"){
for(var i=0,n=x.length;i<n;i++){
let=x.charAt(i);
pos=someAscii.indexOf(let)+32;
h16=Math.floor(pos/16);
h1=pos%16;
r+=hex.charAt(h16)+hex.charAt(h1);
}
}
if(alg=="H2A"){
for(var i=0,n=x.length;i<n;i++){
let1=x.charAt(2*i);
let2=x.charAt(2*i+1);
val=hex.indexOf(let1)*16+hex.indexOf(let2);
r+=someAscii.charAt(val-32);
}
}
return r;
}
console.log(AscHex('65','A2H')); // A
不隶属于 StackOverflow