Last active
April 17, 2019 17:10
-
-
Save aaroneiche/3895d9fceca475e9c017ada8e2bc1c25 to your computer and use it in GitHub Desktop.
Some experiments in manipulating bytes for an LED Driver. Javascript because it's fast and easy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
I wrote this to do some experimentation on | |
bit manipulation. I'm faster in Javascript than I am in C | |
and this let me work out the logic for shifting | |
the bits into the right positions. | |
The goal was to turn an integer into an on/off state | |
for the NXP9532D - an LED driver. | |
(https://www.nxp.com/docs/en/data-sheet/PCA9532.pdf - see page 8) | |
If I have a number, 5 in binary: 1001 | |
that turns into a 1-byte value with two bits for each number. | |
A 1 becomes a 10 (setting the value to PWM0 rate) | |
So a 1001 | |
to LS0 becomes 1000 0010 | |
A 22: 0001 0110 | |
becomes | |
LS1: 0000 0010 | |
LS0: 0010 1000 | |
*/ | |
//This is just a simple method for displaying numbers in binary | |
let b = (num) => { | |
return num.toString(2).padStart(8,0).slice(0,4) + " " + num.toString(2).padStart(8,0).slice(4,8) | |
} | |
var v = 22; // 0001 0110 | |
var n1 = v & 15; // lower nibble: 15 = 0000 1111 | |
var n2 = (v & 240) >> 4; // upper nibble: 240 = 1111 0000 - then shifted right | |
var lower = 0; | |
var upper = 0; | |
/* | |
// This is a programmatic method of stepping through the | |
// bits, and shifting out | |
var c = 4 | |
while(c > 0) { | |
// console.log(b(8 & n1)); | |
if((8 & n1)) { // 8 AND'd with the nibble tells us if there's a 1 in the 8 position | |
lower = ((1 << (c * 2 - 1) ) | lower); //OR the | |
//c is the position of the bit. | |
console.log(`c is ${c}. New position is: ${b(1 << (c * 2 - 1))}. lower is now ${b(lower)}`); | |
} | |
n1 = n1 << 1 //shift right by 1. | |
c--; | |
} */ | |
/* | |
Example: | |
If 4 bit is true | |
Shift a bit into 32 bit | |
Combine with the existing lower | |
*/ | |
// This isn't as programatically attractive, but is more efficient. | |
if((8 & n1)) lower = ((1 << 7) | lower); | |
if((4 & n1)) lower = ((1 << 5) | lower); | |
if((2 & n1)) lower = ((1 << 3) | lower); | |
if((1 & n1)) lower = ((1 << 1) | lower); | |
console.log(b(lower)); | |
//0010 1000 | |
if((8 & n2)) upper = ((1 << 7) | upper); | |
if((4 & n2)) upper = ((1 << 5) | upper); | |
if((2 & n2)) upper = ((1 << 3) | upper); | |
if((1 & n2)) upper = ((1 << 1) | upper); | |
console.log(b(upper)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment