简体   繁体   中英

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. This is for decoding and encoding PICO-8 cartridges ( see here ), which stores the program data in PNG images. 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/

Greatly appreciate any help on this, thanks!

To get the last two bits, try value & 3 rather than 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. 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:

...
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);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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