在javascript中从一个字节中获取两个半字节的最佳方法?

发布于 2024-09-24 02:46:38 字数 282 浏览 13 评论 0原文

我正在用 javascript 解析一个二进制文件,该文件每个字节存储两条信息,每个半字节一条信息。当然,这些值是 0-16 和 0-16。

在文件格式的所有其他部分中,每个字节代表一条信息,因此我一直在使用以下内容来成功获取我需要的数值:

var num = str.charCodeAt(0) & 0xFF;

但我一直在尝试弄清楚如何获取 0-16第一个半字节的值,以及我的单字节字符“str”中的第二个半字节的值。

感谢对此的任何帮助。

I'm parsing a binary file in javascript that is storing two pieces of information per byte, one per nibble. The values are, of course, 0-16 and 0-16.

In all other parts of the file format, each byte represents one piece of information, so I have been using the following to successfully get the number values I need:

var num = str.charCodeAt(0) & 0xFF;

But I'm stuck at trying to figure out how to get the 0-16 value of the first nibble, and the same for the 2nd nibble from my single byte character "str".

Appreciate any help on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

肩上的翅膀 2024-10-01 02:46:38
var num = str.charCodeAt(0) & 0xFF;
var nibble1 = num & 0xF;
var nibble2 = num >> 4;
var num = str.charCodeAt(0) & 0xFF;
var nibble1 = num & 0xF;
var nibble2 = num >> 4;
趁年轻赶紧闹 2024-10-01 02:46:38

你可以这样做:

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)。

You can do:

var num = str.charCodeAt(0);
var lower_nibble = (num & 0xF0) >> 4;
var higher_nibble = num & 0x0F;

How does it work?

Lets suppose the bit representation of num is abcdwxyz and we want to extract abcd as higher nibble and wxyz as lower nibble.

To extract the lower nibble we just mask the higher nibble by bitwise anding the number with 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.

To extract the higher nibble we first mask the lower nibble by bitwise anding with 0xF0 as:

a b c d w x y z
              &
1 1 1 1 0 0 0 0
---------------
a b c d 0 0 0 0

and then we bitwise right- shift the result right 4 times to get rid of the trailing zeros.

Bitwise right shifting a variable 1 time will make it loose the rightmost bit and makes the left most bit zero:

a b c d w x y z 
           >> 1
----------------
0 a b c d w x y

Similarly bitwise right shifting 2 times will introduce result in :

a b c d w x y z 
           >> 2
----------------
0 0 a b c d w x

and bitwise right shift 4 times gives:

a b c d w x y z 
           >> 4
----------------
0 0 0 0 a b c d 

as clearly seen the result is the higher nibble of the byte (abcd).

吖咩 2024-10-01 02:46:38

因为我喜欢这个,所以我想添加一些我刚刚写的可能有用的东西。也许其他人也会发现它很有用。

下面的 jsFiddle

原型:


   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

Since I'm favoriting this, I wanted to add some things I just wrote that might be useful. Perhaps others will find it useful as well.

Below's jsFiddle

Prototypes:


   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;
                                                  };

Example Calls:


   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 ]
   
   

Just added for possible help, but is not used in the above:


/* 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
云雾 2024-10-01 02:46:38

将字符串转换为缓冲区,然后转换为乳头:

function bufferToNibbles(key) {
  // this will convert ascii string to hex values 
  // buffer will get sequence of bytes
  const buffer = Buffer.from(key);
  const nibbles = [];
  for (let i = 0; i < buffer.length; i++) {
    let q = i * 2;
    nibbles[q] = buffer[i] >> 4;
    ++q;
    nibbles[q] = buffer[i] % 16;
  }
  return nibbles;
}

Convert the string to buffer and then nipples:

function bufferToNibbles(key) {
  // this will convert ascii string to hex values 
  // buffer will get sequence of bytes
  const buffer = Buffer.from(key);
  const nibbles = [];
  for (let i = 0; i < buffer.length; i++) {
    let q = i * 2;
    nibbles[q] = buffer[i] >> 4;
    ++q;
    nibbles[q] = buffer[i] % 16;
  }
  return nibbles;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文