Friday
Jan 16,2009
有时在跨架构porting的时候,如X86 To ARM, 内存的对齐问题并非如我们所愿,所以在用Gcc compiler的时候,要尽量使用__attribute__ ((__packed__)),比如:
struct ib_net_radio_t {
unsigned char word[2];
unsigned char packet;
unsigned char check;
unsigned char proto[2];
unsigned char payload[0];
}__attribute__ ((__packed__));
在ARM下用Gcc 2.9编译,如果不加上__attribute__ ((__packed__)),sizeof(struct ib_net_radio_t) == 8,加上之后,就是6. 在转packet的format的时候,这个得分外注意。
Tags:
code,
Programming
Friday
Dec 12,2008
很多时候在调试code的时候,需要把内存数据同时以16进制和ASCII形式列印出来,比如网络封包、结构体的内容、buf内容等等,(当然IDE用户可以跳过忽视),所以写一个dump data的function来用。
原型为:
void dump_data(char* datastartp, const size_t maxlen);
其中,datastartp可以由其他类型的指针转换过来,比如一个struct,转换之后只是让他可以按字节流输出其内容。
源码:
- void
- dump_data(char* datastartp, const size_t maxlen)
- {
- char line[(( (7+1+16*3+2+16+2) +3)/4)*4];
- char* linep;
- const unsigned char* datap;
- size_t len, i, inc=0;
-
- len = maxlen;
- datap = datastartp;
-
- while (len > 0)
- {
- memset(line, ' ', sizeof(line));
- sprintf(line, "%07x:", inc);
- inc++;
-
- linep = &line[7+1];
- for (i = 0; i < 16; i++)
- {
- if (i >= len)
- break;
- sprintf(linep, " %02x", datap[i]);
- linep += 3;
- }
- *linep = ' ';
-
- linep = &line[7+1+16*3+2];
- for (i = 0; i < 16; i++)
- {
- if (i >= len) break;
- if (isprint((char)datap[i]))
- *linep++ = (char)datap[i];
- else
- *linep++ = '.';
- }
-
- line[7+1+16*3+2+16+0] = '\n';
- line[7+1+16*3+2+16+1] = '\0';
- printf(line);
-
- datap += 16;
- if (len >= 16)
- len -= 16;
- else
- len = 0;
- }
- }
如何调用:
- struct ib_net_radio_t {
- unsigned char word[2];
- unsigned char packet;
- unsigned char check;
- unsigned char proto[2];
- unsigned char payload[0];
- };
-
- char* output;
-
- output = (char*)radio; //可以使用任意类型,只要将其强制转换到char*即可;
- printf("Dump Data:\n");
- dump_data(output, total_len);
输出结果如下:
- Dump Data:
- 0000000: 08 22 01 dd 08 06 00 01 08 00 06 04 01 fb 00 c0 ."...........??
- 0000001: ee 0c 11 fe c0 a8 fa 0a 00 00 00 00 00 00 00 00 ....括..........
- 0000002: 00 00 ..
Tags:
code,
Programming
Thursday
Sep 18,2008
主机字节序和网络字节序的转换只要更改p[]的顺序即可。
- unsinged long int ipstring2long(const char *ipstr)
- {
- int ip[4];
- int matches;
- unsinged long int tmp;
- unsigned char *p = (unsigned char*)&tmp;
-
- matches = sscanf(ipstr, "%u.%u.%u.%u", &ip[0], &ip[1], &ip[2], &ip[3]);
- if ( matches != 4 )
- {
- return (unsigned long int) - 1;
- }
- else
- {
- p[3] = ip[0];
- p[2] = ip[1];
- p[1] = ip[2];
- p[0] = ip[3];
- return tmp;
- }
-
- }
Tags:
code,
development