Convert::Binary::C で C 構造体をバイナリ変換 (共用体)
C 共用体をバイナリ変換する。
ヘッダファイル
union.h
#ifndef _UNION_H_ #define _UNION_H_ typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; #pragma pack(1) struct top_t { union { u_char byte[2]; u_short word; } uni; }; #pragma pack #endif /* _UNION_H_ */
変換前のデータ
共用体のメンバのどちらかに、値を入れておく。
my %test_data = ( uni => { byte => [ 0x01 ] } );
pack
my $packed = $c->pack( 'top_t', \%test_data ); print hexdump( data => $packed );
0x0000 : 01 00 : ..
unpack
my $unpacked = $c->unpack( 'top_t', $packed ); print Dumper($unpacked);
$VAR1 = { 'uni' => { 'byte' => [ 1, 0 ], 'word' => 256 } };
テストコード
#!/usr/bin/perl use strict; use warnings; use Carp; use Convert::Binary::C; use Data::Dumper; use Data::Hexdumper; my $c = Convert::Binary::C->new(); $c->configure( ByteOrder => 'BigEndian' ); $c->parse_file('./union.h'); # data my %test_data = ( uni => { byte => [ 0x01 ] } ); # pack my $packed = $c->pack( 'top_t', \%test_data ); print '--- pack', $/; print hexdump( data => $packed ); # unpack my $unpacked = $c->unpack( 'top_t', $packed ); print '--- unpack', $/; print Dumper($unpacked);
--- pack 0x0000 : 01 00 : .. --- unpack $VAR1 = { 'uni' => { 'byte' => [ 1, 0 ], 'word' => 256 } };