Languages
[Edit]
EN

JavaScript - get and set bits in byte array

12 points
Created by:
Laylah-Walsh
534

In this article, we would like to show how in JavaScript get and set bits in a byte array.

To understand the below code it is necessary to know how bytes and bits are indexed.

NOTATION (the way we write and address bytes and bits):

//  Byte index:                                   0           1           2
//  Bit index:                                |7     |0   |15    |8   |23    |16
//                                            v      v    v      v    v      v
//  DEC values:  170, 175, 10    BIN values:  10101010    10101111    00001010

Practical example:

// ONLINE-RUNNER:browser;

function getBits(number, length) {
	var text = '';
  	for (var i = length - 1; i > -1; --i) {
    	text += 0x01 & (number >> i);
    }
  	return text;
}

function BitArray(byteArray) {
  	this.getSize = function() {
    	return 8 * byteArray.length;
    };
	this.getBit = function(index) {
    	var byteIndex = Math.floor(index / 8);
      	var bitIndex = index - 8 * byteIndex;
      	var byteValue = byteArray[byteIndex];
      	if (byteValue < 0 || byteValue > 255) {
        	throw new Error('Array item must be byte (in range: 0-255).');
        }
      	var bitValue = (byteValue >>> bitIndex) & 0x01;
      	return bitValue;
    };
  	this.setBit = function(index, value) {
    	var byteIndex = Math.floor(index / 8);
      	var bitIndex = index - 8 * byteIndex;
      	var byteValue = byteArray[byteIndex];
      	if (byteValue < 0 || byteValue > 255) {
        	throw new Error('Array item must be byte (in range: 0-255).');
        }
      	var maskValue = 0x01 << bitIndex;
      	byteArray[byteIndex] = value ? (byteValue | maskValue) : (byteValue & ~maskValue);
    };
  	this.toString = function(delimiter) {
      	if (delimiter == null) {
        	delimiter = ' ';
        }
    	var result = '';
      	for (var i = 0; i < byteArray.length; ++i) {
          	if (i > 0) {
            	result += delimiter;
            }
          	var byte = byteArray[i];
          	if (byte < 0 || byte > 255) {
        		throw new Error('Array item must be byte (in range: 0-255).');
        	}
          	result += getBits(byte, 8);
        }
      	return result;
    };
}


// Usage example:

//  Byte index:                                0           1           2
//  Bit  index:                            |7     |0   |15    |8   |23    |16
//                                         |      |    |      |    |      |
//           DEC:                     BIN: v      v    v      v    v      v
var byteArray = [170, 175, 10];  //       [10101010,   10101111,   00001010]

var bitArray = new BitArray(byteArray);

// bits getting:

console.log(0 + '\t' + bitArray.getBit(0));  // 0	0
console.log(1 + '\t' + bitArray.getBit(1));  // 1	1
console.log(2 + '\t' + bitArray.getBit(2));  // 2	0
console.log(3 + '\t' + bitArray.getBit(3));  // 3	1

console.log(bitArray.toString());  // 10101010 10101111 00001010

// bits setting (before: 10101010, after: 10100101):

bitArray.setBit(0, 1);
bitArray.setBit(1, 0);
bitArray.setBit(2, 1);
bitArray.setBit(3, 0);

console.log(byteArray[0]);  // 165  <--- DEC

//                                         |7     |0
//                                         |      |
//                                         v      v
console.log(getBits(byteArray[0], 8));  // 10100101  <-- BIN

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join