Skip to content

Instantly share code, notes, and snippets.

@bitsgalore
Last active April 13, 2018 19:06
Show Gist options
  • Save bitsgalore/0f2d33492fb576720f94f0e4221efbbc to your computer and use it in GitHub Desktop.
Save bitsgalore/0f2d33492fb576720f94f0e4221efbbc to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import random
import struct
import base64
# Create list of random floating point values
listFloatIn = []
for i in range(20):
numberIn = random.uniform(0, 1)
listFloatIn.append(numberIn)
# Pack all floats in list into one bytes object
# (8 bytes for each number, big-Endian byte order)
bufIn = struct.pack('!%sd' % len(listFloatIn), *listFloatIn)
# Encode bytes object to URL-safe base64 (returns bytes object)
bufInBase64 = base64.urlsafe_b64encode(bufIn)
# Decode base64 encoded data back to original bytes object
bufOut = base64.urlsafe_b64decode(bufInBase64)
# Create output list
listFloatOut = []
# Iterate over decoded bytes object, and unpack 8 bytes at a time
offset = 0
for i in range(int((len(bufOut))/8)):
# Unpack 8 bytes at a time
numberOut = struct.unpack('!d', bufOut[offset:offset+8])[0]
listFloatOut.append(numberOut)
offset +=8
# Print base64 encoded data to screen (decoding to ascii first)
print("---\nBase 64 encoded string:")
print(bufInBase64.decode('ascii'))
print("---\n")
# Print table with values from listFloatIn versus corresponding
# values in listFloatOut
print("{:<20} {:<20}".format("numberIn", "numberOut"))
print("-----------------------------------")
for i in range(len(listFloatIn)):
print("{:<20} {:<20}".format(listFloatIn[i], listFloatOut[i]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment