#!/bin/env python3 def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def bits_to_hex(bits): if len(bits) % 8: raise RuntimeError('Wrong number of bits') parts = [bits[i:i+8] for i in range(0, len(bits), 8)] return ','.join("0x{:02x}".format(int(section, 2)) for section in parts) def triple(string): for character in string: yield character yield character yield character if __name__ == "__main__": import argparse as ap import random as rnd class NoiseAction(ap.Action): def __call__(self, parser, namespace, values, option_string=None): if values < 0 or values > 1: parser.error("allowed noise values are from the interval [0, 1]") setattr(namespace, self.dest, values) parser = ap.ArgumentParser(description='Script for generating inputs for the isu8-cv5-1 practice') parser.add_argument('input', type=str, help='string to be encoded') parser.add_argument('-n', '--noise', dest='noise', action=NoiseAction, type=float, default=0.5, help='channel noise level (0 = no noise, 1 = maximum noise, 0.5 by default)') parser.add_argument('-u', '--unsafe', dest='unsafe', action='store_true', help='allow for a message corruption (noise value of 1 implies a random output with this option)') # parse input arguments args = parser.parse_args() # get a bit representation of the input bits = text_to_bits(args.input) # triple each bit, convert to list bitlist = list(triple(bits)) #print(''.join(bitlist)) # flip some bits args.noise = args.noise / 2 if args.noise > 0: if args.unsafe: # determine a random flip for each of the bit for i in range(len(bitlist)): if rnd.random() > args.noise: continue if bitlist[i] == '0': bitlist[i] = '1' else: bitlist[i] = '0' else: # determine a random flip for a single bit in each group for i in range(0, len(bitlist), 3): if rnd.random() > args.noise: continue i += rnd.randrange(3) if bitlist[i] == '0': bitlist[i] = '1' else: bitlist[i] = '0' # encode the bits to hex #print(''.join(bitlist)) print(bits_to_hex(''.join(bitlist)))