Skip to content

Latest commit

 

History

History
90 lines (64 loc) · 2.4 KB

README.md

File metadata and controls

90 lines (64 loc) · 2.4 KB

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

Installation

Leiningen:

[com.evanjbowling/bits "0.0.1"]

Demo

Start a REPL with this lib (WARN: only do this for dependencies you trust!):

clj -Sdeps '{:deps {com.evanjbowling/bits {:mvn/version "0.0.1"}}}'

Load the namespace:

(require '[com.evanjbowling.bits :as bits])

View the binary encoding for a few shorts:

(require '[clojure.pprint :as pp])
(require '[clojure.string :as str])

(defn print-shorts [shorts]
  (let [max-s (apply max (map (comp count str) shorts))]
    (doseq [s shorts]
      (let [padded-val (pp/cl-format nil (str "~" max-s "@a") s)
            ->str (fn[x](str/join "" x))]
        (printf "%s %s\n"
          padded-val
          (->str (bits/short-bits (short s))))))))

(print-shorts [Short/MIN_VALUE -1 0 1 Short/MAX_VALUE])
-32768 1000000000000000
    -1 1111111111111111
     0 0000000000000000
     1 0000000000000001
 32767 0111111111111111

Examine some chars:

(->> [\A \B \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 0 0 0 0 1 0)
;  (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 (float 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])

(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

; make the exponent all ones for Infinity:
(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

; then set a fraction bit to make a NaN:
(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-2024 Evan Bowling

Distributed under the MIT License