Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AnastasiaDunbar/fc2780dba6b636c37a298ea5a20402db to your computer and use it in GitHub Desktop.
Save AnastasiaDunbar/fc2780dba6b636c37a298ea5a20402db to your computer and use it in GitHub Desktop.
//JavaScript uses 32-bits bitwise operands on 64-bits floating-point numbers.
function readBitsLE(bytes,at,size){
let b=Math.floor(at/8),shift=Math.floor(at)%8,
mask=size>=32?4294967295:(1<<size)-1;
return((
(bytes[b]|bytes[b+1]<<8|bytes[b+2]<<16|bytes[b+3]<<24)>>>shift|
Math.floor(bytes[b+4])*Math.pow(2,32-shift)
)&mask)>>>0;
}
function writeBitsLE(bytes,at,size,value){
let b=Math.floor(at/8),shift=at%8,
mask=size>=32?4294967295:(1<<size)-1,
length=1+Math.floor(((size+shift)-1)/8);
value&=mask;
bytes[b]=((bytes[b]&~(mask<<shift))|(value<<shift))&255;
for(let i=1;i<length;i++)
bytes[b+i]=((bytes[b+i]&~(mask>>>((8*i)-shift)))|value>>>((8*i)-shift))&255;
}
function mod(a,b){return(a%b+b)%b;}
var leftShift =(n,s)=>s>-32&&s<32?s<0?n>>>-s:(n<<s)>>>0:0,
rightShift=(n,s)=>s>-32&&s<32?s<0?(n<<-s)>>>0:n>>>s:0;
function readBitsBE(bytes,at,size){
let b=Math.floor(at/8),shift=mod(Math.floor(at),8),mask=size>=32?4294967295:(1<<size)-1;
return((
leftShift(bytes[b ],size+shift- 8)|leftShift(bytes[b+1],size+shift-16)|
leftShift(bytes[b+2],size+shift-24)|leftShift(bytes[b+3],size+shift-32)|
leftShift(bytes[b+4],size+shift-40))&mask)>>>0;
}
function writeBitsBE(bytes,at,size,value){
let b=Math.floor(at/8),shift=mod(Math.floor(at),8),mask=size>=32?4294967295:(1<<size)-1,
length=Math.ceil((size+shift)/8);
value&=mask;
bytes[b]=((bytes[b]&~leftShift(mask,8-shift-size))|leftShift(value,8-shift-size))&255;
for(let i=1;i<length;i++)
bytes[b+i]=((bytes[b+i]&~leftShift(mask,(8*(i+1))-shift-size))|leftShift(value,(8*(i+1))-shift-size))&255;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment