March 9: Bitwise operations in a weakly-typed programming language

  • what makes 0 and 1 special and different from other numbers, and why they’re so important
  • how one manipulates zeroes and ones in a computer programming language (and why)
  • some practical examples of bit manipulation and limitations thereof in a dynamically-typed programming language (like JavaScript)

Background: Computers have fingers

Photo credit: 20th Century Fox
Photo credit: Mario Kaack (ShortRope.com)

You’ve come a long way, baby

Designed in 1974 by Ed Roberts, the Altair 8800 was sold as a kit by mail-order for $429. The switches are for entering binary data; the LEDs are for displaying binary data. Later software, including among the first products developed by Microsoft, allowed for more sophisticated input/output. Today a working 8800 fetches as much as five figures at auction! (Photo Credit: Smithsonian/National Museum of American History)

She’s got a type

  • AND & sets each bit in the result only if both bits are set in the operands
  • OR | sets each bit in the result if the bit in question is set in either of the operands
  • XOR ^ sets each bit in the result only if the bit is set in one (but not both or neither) of the operands
  • LSH << shifts bits set to the left, filling in zeroes on the right
  • RSH >> shifts bits set to the right, filling in zeroes on the left

Conclusion: Fun and profit

function min( x, y ) { return y ^ ( ( x ^ y ) & -( x < y ) ); }function max( x, y ) { return x ^ ( ( x ^ y ) & -( x < y ) ); }function oppositeSigns( x, y ) { return !!( x ^ y ); }function isPowerOfTwo( x ) { return x && !( x & ( x - 1 ) ); }
function countBits( number ) {
let counter = number - ( ( number >> 1 ) & 3681400539 ) - ( ( number >> 2 ) & 1227133513 );
return ( ( counter + ( counter >> 3 ) ) & 3340530119 ) % 63;
}

--

--

--

Oh geez, Josh Frank decided to go to Flatiron? He must be insane…

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Next Challenge: Single Page App

Programming Courses : Should I ?

Drawing a Parallel Between Linux and Blockchain

The app to transform the world, the financial world at least. Apadrinapp!

Your Email Inbox Controls U, Not the Other Way Around

Zeppelin 0.8.0 New Features

Insurance Dao Tester Experience

Google Analytics Calculated Metrics in Use

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Josh Frank

Josh Frank

Oh geez, Josh Frank decided to go to Flatiron? He must be insane…

More from Medium

2 Dynamic Ways To Express Chemistry’s Relationship With The Real World.

My Intro To Coding

Languages for coding :

Using PL/SQL Subprograms