Skip to content

Instantly share code, notes, and snippets.

@kwilcox
Created August 1, 2017 18:20
Show Gist options
  • Save kwilcox/87af72559e16bbc135a6f96535311627 to your computer and use it in GitHub Desktop.
Save kwilcox/87af72559e16bbc135a6f96535311627 to your computer and use it in GitHub Desktop.
Takes Cambell Scientific High Resolution 18-Bit Binary Format and converts it to a CSV row
def decode_campbell_18_bit_binary_message(bites):
"""
Takes Cambell Scientific High Resolution 18-Bit Binary Format and converts
it to a CSV row.
"""
row = []
while True:
# Number are three bytes long
byte_s = bites.read(3)
if not byte_s:
break
# logger.debug('Bytes: {}'.format(byte_s, type(byte_s)))
members = []
for i, b in enumerate(byte_s):
# binary = '{0:08b}'.format(b)
# logger.debug('Binary {}: {}'.format(i, binary))
# Apply mask to remove first two bits
mask = 0b00111111
masked = mask & b
masked_bin = '{0:08b}'.format(masked)[2:]
# logger.debug('Masked {}: {}'.format(i, masked_bin))
members.append(masked_bin.encode())
sofar = b''.join(members)
# logger.debug('Combined mask: {}'.format(sofar))
integ = int(sofar, 2)
# This correctly subtracts one and takes the complement if
# the value should be negative per the Campbell Scientific docs
# It's a typical two's complement
# http://stackoverflow.com/a/9147327
bits = 18
if (integ & (1 << (bits - 1))) != 0:
integ = integ - (1 << bits)
row.append(str(integ))
return ','.join(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment