Skip to content

evanjbowling/bits

Repository files navigation

bits

A smallish Clojure library for transforming Java primitives into binary sequences and back again. Intended to help explore encodings. Particularly useful for float and double types.

Build Status Dependencies Status

Clojars Project

Install

Leiningen/Boot:

[com.evanjbowling/bits "0.0.1"]

Clojure CLI/deps.edn:

com.evanjbowling/bits {:mvn/version "0.0.1"}

Quick Demo

Load the namespace:

(ns whose.ns
  (:require [com.evanjbowling.bits :as bits]))

View the binary encoding for a few shorts:

(->> ["7" "0" "-1"]
     (map bits/short-bits)
     clojure.pprint/pprint)

; ((0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1)
;  (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
;  (1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1))

Examine some chars:

(->> ["A" "a" "µ"]
     (map bits/char-bits)
     clojure.pprint/pprint)

; ((0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1)
;  (0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1)
;  (0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 1))

The floating point bit sequences are grouped [[sign] [exponent] [fraction]]:

(bits/float-bits "0.25")

; ([0] [0 1 1 1 1 1 0 1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0])

You can convert the bit sequence back to it's original form:

(bits/from-float-bits '([0] [0 1 1 1 1 1 0 1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]))

; 0.25

This is a great way to see what happens when you make the exponent all ones:

(bits/from-float-bits '([0] [1 1 1 1 1 1 1 1] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]))

; Infinity

And then tweak the fraction bits too:

(bits/from-float-bits '([0] [1 1 1 1 1 1 1 1] [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]))

; NaN

License

Copyright © 2019 Evan Bowling

Distributed under the MIT License

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published