專案中需要建立乙個二進位制檔案,檔案大小為512kb,檔案的每乙個位元組初始化為0xff,沒找到比較方便的工具,就l寫了個shell指令碼,順便熟悉下shell程式設計。
#!/bin/bash
# author: lizhi
# date: 2012-09-25-11:33
# file: create-my-file.sh
# description: create binary file and init dada and size;
# eg. size:1kb name:test file created by command:
# ./create-my-file.sh test -byte ff 1024
# every byte value 0xff
if [ $# -ne 4 ];then
echo "use format: $0 filename datatype[-string -decimal -octal -hex -bit -byte] initdata initcount"
echo "datatype: define the \"initdata\" data \type,used:"
echo " -string fill file with any bytes string data "
echo " -decimal fill file with 4 bytes decimal number "
echo " -octal fill file with 4 bytes octal number"
echo " -hex fill file with 4 bytes byte data,eg. ffffffff "
echo " -bit fill file with 1 byte data,eg. 11101101 "
echo " -byte fill file with 1 byte data,eg. ff "
echo "initdata: set the init data,fill file with this dada"
echo "initcount: filled count"
exit 1
fifilename=$1
datatype=$2
initdata=$3
initcount=$4
echo "filename=$filename datatype=$datatype initdata=$initdata initcount=$initcount"
# string data type
if [ "$datatype" == "-string" ]; then
datalen='expr length $initdata'
echo "data length $datalen"
counter=0
while [ "$counter" -lt "$initcount" ]
do
echo -n $initdata >> $filename
((counter++))
echo "counter=$counter initdata=$initdata"
done
exit 0
fi# other data type
hexdata=$initdata
if [ "$datatype" == "-decimal" ]; then
hexdata=`echo "ibase=10; obase=16; $initdata" | bc`
elif [ "$datatype" == "-octal" ]; then
hexdata=`echo "ibase=8; obase=16; $initdata" | bc`
elif [ "$datatype" == "-bit" ]; then
hexdata=`echo "ibase=2; obase=16; $initdata" | bc`
elif [ "$datatype" != "-byte" ] && [ "$datatype" != "-hex" ]; then
echo "datatype error"
exit 1
fiecho "hexdata=$hexdata"
# format data as ffffffff
format_hexdata=`printf "%08x" 0x$hexdata`
echo "format_hexdata=$format_hexdata"
# sed parttern
if [ "$datatype" == "-bit" ] || [ "$datatype" == "-byte" ]; then
sed_partten="`echo $format_hexdata | sed 's/[0-9a-za-z]\/& /g' | awk ''`"
else
sed_partten="`echo $format_hexdata | sed 's/[0-9a-za-z]\/& /g' | awk ''`"
fiecho "sed_partten=$sed_partten"
# write file,begin 0pos write 1byte
counter=0
while [ $counter -lt $initcount ]
doecho -e -n "$sed_partten" >> $filename # -n: no newline; -e: enable interpretation of backslash escapes
((counter++))
done
echo "successed"
exit 0
二進位制檔案
本質上是文字檔案是把檔案資訊先轉化成以字元編碼的ascii碼,再儲存ascii的二進位制 而二進位制檔案是直接把檔案資訊編碼成二進位制儲存。因此在讀取的時候要考慮記憶體中二進位制 應該怎麼樣解釋。二進位制檔案的讀取是是要告訴元素的型別 編碼方式 文字檔案則預設為char型別。文字檔案是一種特殊的二進...
二進位制檔案
二進位制檔案 也叫型別檔案 二進位制檔案是由一批同一型別的資料組成的乙個資料序列,就是說乙個具體的二進位制檔案只能存放同一種型別的資料。type tmember record name string 10 email string 20 posts longint end var members a...
二進位制檔案
二進位制檔案 也叫型別檔案 二進位制檔案是由一批同一型別的資料組成的乙個資料序列,就是說乙個具體的二進位制檔案只能存放同一種型別的資料。type tmember record name string 10 email string 20 posts longint end var members a...