简体   繁体   English

如何获得一个字节的最后2位

[英]How to get the last 2 bits in a byte

In an array of bytes, such as [40, 0, 156, 243] , I need to make 1 byte from the last two bits in each byte of the array. 在字节数组中,例如[40, 0, 156, 243] ,我需要从数组的每个字节的最后两位中提取1个字节。 This is for decoding and encoding PICO-8 cartridges ( see here ), which stores the program data in PNG images. 这用于解码和编码PICO-8盒带( 请参阅此处 ),该盒带将程序数据存储在PNG图像中。 Here is the information that I've been given on how the data is stored: 以下是有关如何存储数据的信息:

For png files, the lower 2 bits of each pixel component makes up one byte, so 1 byte per pixel. The last 32 bytes are metadata for the PNG (since 160*205 = 0x8020, 32 extra bytes) byte = (a << 6) | (r << 4) | (g << 2) | b;

Here's what I have so far, but the output is all gibberish: 这是我到目前为止的内容,但是输出都是乱码:

var imgWidth  = 160;
var imgHeight = 205;
var canvas    = document.createElement('canvas');
var ctx       = canvas.getContext('2d');
var img       = document.createElement('img');

img.src = 'Invasion.png';

canvas.width  = imgWidth;
canvas.height = imgHeight;

img.onload = function() {
  var imgData = [];
  var str     = '';
  var i = 0, n = 0, dataLen = 0;

  ctx.drawImage(img, 0, 0);

  imgData = ctx.getImageData(0, 0, imgWidth, imgHeight).data;
  dataLen = imgData.length;

  for(i; i < dataLen; i+=4) {
    var r = imgData[i];
    var g = imgData[i + 1];
    var b = imgData[i + 2];
    var a = imgData[i + 3];

    r = (r & 3) << 4;
    g = (g & 3) << 2;
    b = (b & 3);
    a = (a & 3) << 6;

    byte = a | r | g | b; // assembled byte

    str += String.fromCharCode(byte);
  }

  console.log(str);
};

Fiddle: https://jsfiddle.net/24o3fzg3/ 小提琴: https : //jsfiddle.net/24o3fzg3/

Greatly appreciate any help on this, thanks! 非常感谢任何帮助,谢谢!

To get the last two bits, try value & 3 rather than value % 100 . 要获取最后两位,请尝试使用value & 3而不是value % 100 ( value % 100 takes the remainder of value after dividing by 100 in decimal, not binary.) You then need to shift those two bits into the appropriate position in the final byte. value % 100用十进制除以100后得到的value的余数,而不是二进制。)然后,您需要将这两位移到最后一个字节中的适当位置。 Something like this: 像这样:

  r = (pixels[n][0] & 3) << 4;
  g = (pixels[n][1] & 3) << 2;
  b = (pixels[n][2] & 3);
  a = (pixels[n][3] & 3) << 6;

  val = a | r | g | b; // assembled byte

(I'm not addressing whether this is the correct order for the bits in the assembled value or the correct pixel array order.) (我没有说明这是汇编值中位的正确顺序还是像素阵列的正确顺序。)

I'm a not an js guy, but I think code should be like this: 我不是一个JS家伙,但是我认为代码应该像这样:

...
r = (pixels[n][0] & 3);
g = (pixels[n][1] & 3);
b = (pixels[n][2] & 3);
a = (pixels[n][3] & 3);
byte = (a << 6) | (r << 4) | (g << 2) | b;
str += String.fromCharCode(byte);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM