Wednesday, December 26, 2012

Perl 의 pack 과 unpack 함수

pack과 unpack 은 데이터를 serialize 하고 그것을 푸는 기능으로, 파일에 읽고 쓰는 작업 등에 쓰기 좋다. 다음과 같은 포맷으로 쓴다.
 LIST = pack TEMPLATE, EXPR
 LIST = unpack TEMPLATE, EXPR  
TEMPLATE 는 다음 형식을 가진다.
 [template characters][repeat number]
template character 에는 A, B, C 등 여러가지가 있는데 예를 들어 C4 이라는 것은 byte 4개를 뜻하고 A10 이라는 것은 ASCII 스트링을 뜻한다. repeat number 를 딱히 정하지 않고 * 로 쓸수도 있다. template character 에는 다음과 같은 것들이 있다.
 A string with arbitrary binary data, will be null padded
 A  A text (ASCII) string, will be space padded
 b  A bit string (ascending bit order inside each byte, like vec()) 
 B  A bit string (descending bit order inside each byte)
 c  A signed char (8-bit) value
 C  An unsigned char (octet) value
 d  A double-precision float in the native format
 f  A single-precision float in the native format
 h  A hex string (low nybble first)
 H  A hex string (high nybble first)
 i  A signed integer value
 I  A unsigned integer value
 l  A signed long (32-bit) value
 L  An unsigned long value
 n  An unsigned short (16-bit) in "network" (big-endian) order
 N  An unsigned long (32-bit) in "network" (big-endian) order
 s  A signed short (16-bit) value
 S  An unsigned short value
 U  A Unicode character number
 v  An unsigned short (16-bit) in "VAX" (little-endian) order
 V  An unsigned long (32-bit) in "VAX" (little-endian) order
 x  A null byte
 X  Back up a byte
사용예 :
다음과 같이 pack 하고
    open (OUTFILE, ">$outfile") or die "error : $!";   
    binmode (OUTFILE);   
       
    $buffer .= pack 'B8', "11110000"; # 240 = 128 + 64 + 32 + 16   
    $buffer .= pack 'B8', "11110001"; # 241   
    $buffer .= pack 'B8', "11110010"; # 242   
    $buffer .= pack 'B8', "11110011"; # 243   
    $buffer .= pack 'C1', 0;   
       
    $buffer .= pack 'C1', 200; # 200   
    $buffer .= pack 'H4', "FEFF"; # 254, 255   
    $buffer .= pack 'C1', 0;   
     
    $buffer .= pack 'A2', "ab";

    print OUTFILE $buffer;   
    close OUTFILE;   
다음과 같이 unpack 한다.
    open (INFILE, "$infile") or die "error : $!";   
    binmode (INFILE);   
       
    my ($buf, $data, $n);   
    for (; ($n = read INFILE, $data, 65536) != 0; $buf .= $data){   
       print "Reading $n bytes from file: $infile\n";   
    }   
    close(INFILE);   
     
    my @buffer;   
    @buffer = unpack('(C1)*', $buf);   
    foreach (@buffer){   
       print();   
       print "\n";   
    }   
Read 한 결과는 다음과 같다.
 Read mode.  
 Reading 11 bytes from file: mytest.bin  
 240  
 241  
 242  
 243  
 0  
 200  
 254  
 255  
 0  
 97  
 98  
 buffer size is 11.  
샘플코드 : Perl 에서 Binary File 읽고 쓰기 샘플 코드
레퍼런스 :
Perl unpack Function
perlpacktut - tutorial on pack and unpack
pack
unpack

No comments:

Post a Comment