Posted by bianbian on 2008-04-20 01:08
本文Tags: binary, bug, pack, php, struct, unpack, 二进制, 数据, 解决
尽管php是用C语言开发的,不过令我不解的是php没有提供对结构体struct的直接支持。
不过php提供了pack和unpack函数,用来进行二进制数据(binary data)和php内部数据的互转:
- string pack ( string $format [, mixed $args [, mixed $...]] )
- //Pack given arguments into binary string according to format.
-
- array unpack ( string $format, string $data )
- //Unpacks from a binary string into an array according to the given format.
其中,$format跟perl里的pack格式类似,有如下一些(中文是我加的,有不准确的欢迎提出):
a NUL-padded string,即“\0”作为“空字符”的表示形式
A SPACE-padded string,空格作为“空字符”的表示形式
h Hex string, low nibble first,升序位顺序
H Hex string, high nibble first,降序位顺序
c signed char,有符号单字节
C unsigned char,无符号单字节
s signed short (always 16 bit, machine byte order)
S unsigned short (always 16 bit, machine byte order)
n unsigned short (always 16 bit, big endian byte order)
v unsigned short (always 16 bit, little endian byte order)
i signed integer (machine dependent size and byte order)
I unsigned integer (machine dependent size and byte order)
l signed long (always 32 bit, machine byte order)
L unsigned long (always 32 bit, machine byte order)
N unsigned long (always 32 bit, big endian byte order)
V unsigned long (always 32 bit, little endian byte order)
f float (machine dependent size and representation)
d double (machine dependent size and representation)
x NUL byte,实际使用的时候作为跳过多少字节用,很有用
X Back up one byte,后退1字节
@ NUL-fill to absolute position,实际使用的时候作为从开头跳到某字节用,很有用
实际使用发现:C里的“\0”(即字符串终止符)在php里并不是终止符,而是作为了字符串的一部分。因此,必须对“\0”进行特殊处理,才能进行struct和php内部数据的完美互转。比如 char name[10]; 如果实际数据是“62 69 61 6E 00 62 69 61 6E 00”,在C语言里第5个位置有终止符,name应该是“bian”;而用了unpack转换以后在php里的name却是“bian\0bian\0”。
一开始我用了strpos函数找到“\0”的位置,然后进行substr截取:
- $name = substr($name, 0, strpos($name, "\0"));
不过很Faint的事情发生了,不知道是strpos的bug还是substr的bug(其实测试一下就知道,懒得试),有些字符串没问题,有些字符串却只能得到空值(即$name == ”)。很是郁闷,后来找了个strtok函数,这下没有问题了:
- $name = strtok($name, "\0");
难为大家看了那么多,下面写个完整的php读取二进制数据流(C语言结构体struct数据)文件的示例代码:
首先是C的struct定义示例,为了演示,我就写个简单点的,实际对照上面那个$format格式表应该没有问题:
- struct BIANBIAN {
- char name[10];
- char pass[33];
- int age;
- unsigned char flag;
- };
比如有个“bianbian.org”文件,内容就是上面的N个BIANBIAN结构体构成的。读取的php代码:
- //下面根据struct确定$format,注意int类型跟机器环境有关,我的32位Linux是4个长度
- $format = 'a10name/a33pass/iage/Cflag';
- //确定一个struct占用多少长度字节,如果只是读取单个结构体这是不需要的
- $length = 10 + 33 + 4 + 1;
- //也可以用fopen + fread + fclose,不过file_get_contents因为可以mmap,效率更高
- $data = file_get_contents('bianbian.org', 'r');
- for ($i = 0, $c = strlen($data); $i < $c; $i += $length) {
- $bianbian = unpack("@$i/$format", $data);
- //reference传递是php 5才支持的,如果用php4,得用其他办法
- foreach ($bianbian as &$value) {
- if (is_string($value)) {
- $value = strtok($value, "\0");
- }
- }
- print_r($bianbian);
- }
- //输出为array,即类似:
- Array
- (
- [name] => 'bianbian'
- [pass] => 'bianbian.org'
- [age] => 100
- [flag] => 0
- )
- ...
pack应该跟unpack相反。
标签:
binary,
bug,
pack,
php,
struct,
unpack,
二进制,
数据,
解决遵守创作共用协议,转载请链接形式注明来自
http://bianbian.org 做人要厚道
相关日志
Posted in Technology, php | 4 Comments »
Posted by bianbian on 2008-04-06 01:36
本文Tags: AJAX, Firefox, JavaScript, XMLHttpRequest, 二进制, 数据
译者注:原来想用JS直接处理C丢过来的struct数据,具体可以查看:[原] C的struct和JSON交互。
经过千辛万苦的查找,找到了这篇文章(作者应该比我更辛苦):Downloading Binary Streams with Javascript XMLHttpRequest
把关键点翻译如下(不过我还没有测试):
利用XMLHttpRequest的overrideMimeType方法设置charset为x-user-defined。
- //fetches BINARY FILES synchronously using XMLHttpRequest
- load_url = function(url) {
- netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
- var req = new XMLHttpRequest();
- req.open('GET',url,false);
- //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
- req.overrideMimeType('text/plain; charset=x-user-defined');
- req.send(null);
- if (req.status != 200) return '';
- return req.responseText;
- }
-
- var filestream = load_url(url);
- var abyte = filestream.charCodeAt(x) & 0xff;
IE不支持overrideMimeType方法,不过有评论者说VBScript可以实现:
- Dim xhr
- Set xhr = CreateObject("Microsoft.XMLHTTP")
- xhr.Open "GET", "folder.bin", False
- xhr.setRequestHeader "Accept-Charset", "x-user-defined"
- xhr.setRequestHeader "Content-Type", "application/pdf"
- xhr.send Null
标签:
AJAX,
Firefox,
JavaScript,
XMLHttpRequest,
二进制,
数据遵守创作共用协议,转载请链接形式注明来自
http://bianbian.org 做人要厚道
相关日志
Posted in JavaScript, Technology | No Comments »
Posted by bianbian on 2006-12-19 06:33
本文Tags: 数据, 涂鸦板
去年用C语言实现的涂鸦板:http://bbs.nju.edu.cn/pntmain
想当年,一夜没睡,不停地debug、截获网络数据,分析涂鸦板oekakibbs和Shi-PainterPRO的数据格式。
最后保存成功带给我的喜悦我是终身难忘。这也是我喜欢编程的部分原因吧。呵呵
oekakibbs和Shi-PainterPRO是比较有名的涂鸦板程序(实际是Java Applet程序),通过http协议和自定义的数据格式往后台提交数据。解析数据网络上比较多的是php和asp的代码,但是因为和彼此自己的系统结合,所以看起来比较费尽。不过从来没有数据格式说明文档。
今天偶然又翻了一下这些代码,顺便在blog里记一下。要是能给其他人省点力气,也算功德一件。呵呵
- #include "www.h"
-
- int pntupload_main()
- {
- int n, i, j, key=0;
- char tmp[80], *buf, tool[30], *p;
- FILE *fp;
-
- chdir(BBSHOME);
- http_header(200);
- printf("Content-type: text/html; charset=gb2312\n\n");
- n = atoi(getsenv("CONTENT_LENGTH"));
- if (n<0 || n>3000000)
- http_fatal("too big");
- buf = malloc(n);
- if(buf==0) http_fatal("out of memory");
- fread(buf, 1, n, stdin); //读入buf
- //-------- 获得_U_KEY
- key = atoi(getsenv("QUERY_STRING"));
- //-------- 获得tool
- p = strchr(getsenv("QUERY_STRING"), '_');
- strsncpy(tool, p+1, 20);
-
- //-------- 根据不同tool, 不同处理数据
- //oekakibbs和oekakibbs2的处理是一样的
- if(!strncmp("oekakibbs", tool, 9))
- {
- //-------- 获得图片
- i = memstr(buf, n, "Content-type:image/0");
- j = memstr(buf+i+24, n, "Content-type:animation/"); //24是"Content-type:image/0\r\n\r\n"的长度
- sprintf(tmp, "paint/tmp/%d.png", key);
- fp = fopen(tmp, "w");
- fwrite(buf + i + 24, 1, j, fp); //j实际是png的长度
- fclose(fp);
- //-------- 获得动画
- j += i+24; //j现在是从buf开始指向Content-type:animation的偏移量
- sprintf(tmp, "paint/tmp/%d.oeb", key);
- fp = fopen(tmp, "w");
- fwrite(buf+j+27, 1, n - j - 27, fp); //p2-buf是长度,27是"Content-type:animation/\r\n\r\n"的长度
- fclose(fp);
- //需要输出success告诉applet保存成功
- printf("success");
- }
- else if(!strcmp("Shi-Painter", tool))
- {
- //png 头:HEX 89 50 4E 47 0D 0A
- //png 尾:HEX 49 45 4E 44 AE 42 60 82
- //unsigned char pngend[] = {0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82};
- i = memstr(buf, n, "\r\n"); //第2行开始就是PNG图片
- j = atoi(buf+1); //buf[0]固定是S,之后就是PNG的长度
- sprintf(tmp, "paint/tmp/%d.png", key);
- fp = fopen(tmp, "w");
- fwrite(buf+i+2, 1, j, fp);
- fclose(fp);
- //-------- 获得动画
- j += i+2; //j现在是从buf开始指向PNG末尾的偏移量
- i = memstr(buf+j, n, "layer_count="); //这里的i就相当于oekakibbs里面的27:就是PNG末尾到layer_count的长度
- sprintf(tmp, "paint/tmp/%d.oeb", key);
- fp = fopen(tmp, "w");
- fwrite(buf+j+i, 1, n-j-i, fp);
- fclose(fp);
- }
- exit(0);
- }
标签:
数据,
涂鸦板遵守创作共用协议,转载请链接形式注明来自
http://bianbian.org 做人要厚道
相关日志
Posted in C/C++, Technology | 1 Comment »