Bytes Align Scrits (Shell & Python)

Shell:

align.sh (未测试) 注意运算符两边要有空格。

#!/bin/bash
file_size=`ls -l $2 | awk '{print $ 5}'`
align_size=`expr $file_size + $1 - 1`
block_num=`expr $align_size / $1`
align_size=`expr $block_num \* $1`
padding_size=`expr $align_size - $file_size`
for((i=0;i<$padding_size;i++));do
printf '\x00' >> $2
done
echo 'padding done..'

run: ./align.sh 16

Python:

align.py (已测试)

#!/usr/bin/env python
import sys,os

if __name__ == '__main__':
    try:
        align_byte = sys.argv[2]
        padding_data = sys.argv[3]
        filename = sys.argv[1]
        file_size = os.path.getsize(filename)
        print "input file size:", file_size
        align_B = int(align_byte,0)
        padding_size = file_size + align_B -1
        padding_size = (padding_size/align_B)*align_B
        padding_size = padding_size - file_size
        print padding_size
        print "padding_data: ",padding_data
        pfile = open(filename,"ab")
        for i in range(0,padding_size):
            pfile.write(chr(int(padding_data,0)))
        pfile.flush()
        pfile.close()
    except:
        print("Error: run error.")
        pass

run: python align.py test_align.bin 16 0xa5

posted @ 2017-04-24 22:46  JustRelax  阅读(173)  评论(0编辑  收藏  举报