Thursday, November 19, 2015

Making a C-array from a sequence of binary.

I've been recently working with the SIMON cipher. There are many nice things about it from a hardware perspective. I came across the need to extract some bits from the paper and put them into a "C" format. The paper gives Z as:
z = [11111010001001010110000111001101111101000100101011000011100110,
10001110111110010011000010110101000111011111001001100001011010,
10101111011100000011010010011000101000010001111110010110110011,
11011011101011000110010111100000010010001010011100110100001111,
11010001111001101011011000100000010111000011001010010011101111]
I took the above and pasted it into a file called "z.txt".
I called the following bash script cformatu.sh.
#!/bin/sh
FILE_NAME=$1 
STR_LENGTH=$(cat $FILE_NAME | tr -d " z=[],\r\n" | wc -c | tr -d '[[:space:]]')
echo "/* bit count is: $STR_LENGTH, generated by cformatu.sh */"
STR_VAL=$(cat $FILE_NAME | tr -d " z=[],\r\n" | sed 's/\(.\{1\}\)/\1,/g' | sed 's/,$//' )
echo "static const u8 z[$STR_LENGTH]={$STR_VAL};"
Using the command "./cformatu.sh z.txt", you will receive the following series to stdout:
/* bit count is: 310, generated by cformatu.sh */
static const u8 z[310]={1,1,1,1,1,0,1,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0,1,1,1,0,0,1,1,0,1,1,1,1,1,0,1,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0,1,1,1,0,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,1,1,1,1,1,0,0,1,0,1,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,0,0,0,1,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0,0,1,1,0,1,0,0,0,0,1,1,1,1,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,0,1,0,1,1,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,1,1,0,1,1,1,1};
The above is so much nicer than actually risking an error when typing it all out.

No comments:

Post a Comment