php struct
1.0.0
php中的結構實現。它支持解碼二進製文件。
創建一個新的結構
$ myStruct_t = new Struct (
" foo " , uint32_t, //single uint32_t
" baz " , uint8_t, 30 //array of 30 unsigned chars
);您可以為成員指定標誌,例如:
$ myStruct_t = new Struct (
" beval " , uint32_t, 1 , ENDIAN_BIG , //big endian value
" leval " , uint32_t, 1 , ENDIAN_LITTLE , //little endian value
" myString " , int8_t, 32 , VAR_STRING , //string of 32 characters
" myNumber " , uint32_t, 1 , VAR_NUMERIC , //explicitly uses the PHP's int type
);您可以使用flag_strsz表示此成員將指定即將到來的字符串的大小
$ string_t = new Struct (
" strSz " , uint32_t, 1 , FLAG_STRSZ , //a string follow, and its length is indicated by this member
" varString " , uint8_t, 0 , //the size will be replaced at runtime due to FLAG_STRSZ
);FLAG_STRSZ的使用使結構大小無法預測。
您也可以使用嵌套結構:
$ myStruct_t = new Struct (
" foo " , uint32_t, //single uint32_t
" baz " , uint8_t, 30 //array of 30 unsigned chars
);
$ otherStruct_t = new Struct (
" magic " , uint8_t, 4 ,
" elements " , $ myStruct_t , 32 , //creates an array of 32 structures
);結構和文件:
// Clone the structure template
$ header = clone ( $ header_t );
// Simple check for proper arguments
if ( $ argc < 2 || ! file_exists ( $ argv [ 1 ])){
fprintf ( STDERR , " File not found! n" );
return 1 ;
}
// Open the specified file in read mode
$ f = fopen ( $ argv [ 1 ], " rb " );
// Get enough data to fill the structure
$ d = fread ( $ f , $ header -> getSize ());
// We don't need the file anymore
fclose ( $ f );
// Put the data we read into the structure
$ header -> apply ( $ d );解析元素
printf ( " Struct size: %d n" , $ header -> getSize ());
foreach ( $ header -> members as $ name => $ member ){
printf ( " member '%s', value: 0x%x n" , $ name , $ member -> getValue ());
}和嵌套結構?
function printStruct ( $ struct ){
foreach ( $ struct -> members as $ name => $ memb ){
$ value = $ memb -> getValue ();
if ( is_array ( $ value )){
if (Struct:: isStructArray ( $ value )){
foreach ( $ value as $ subStruct ){
printStruct ( $ subStruct );
}
} else {
//print array of bytes/elements
printf ( " %s n" , $ name );
var_dump ( $ value );
}
} else {
//print element/value
printf ( " %s => 0x%x n" , $ name , $ value );
}
}
}獲取成員/結構的二進制數據
$ binaryData = $ member -> getData ();設置成員的二進制數據(使用此數據設置字符串!)
$ member -> setData ( $ binData );獲取成員的解碼值(根據其類型)。
$ value = $ member -> getValue ();設置成員的值(將根據其類型進行編碼)。
注意:對於字符串,請使用setData,否則您需要將字符陣列傳遞給此功能
$ member -> setValue ( $ value );