Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How can I write code to conform to these old, binary data file formats?
How can I write code to conform to these old, binary data file formats?
✍: Guest
It's hard, because of word size and byte order differences, floating-point formats, and structure padding. To get the control you need over these particulars, you may have to read and write things a byte at a time, shuffling and rearranging as you go. (This isn't always as bad as it sounds, and gives you both portability of your code and complete control.)
For example, to read a data structure consisting of a character, a 32-bit integer, and a 16-bit integer, from the stream fp, into the C structure
struct mystruct {
char c;
long int i32;
int i16;
} s;
you might use code like this:
s.c = getc(fp);
s.i32 = (long)getc(fp) << 24;
s.i32 |= (long)getc(fp) << 16;
s.i32 |= (unsigned)(getc(fp) << 8);
s.i32 |= getc(fp);
s.i16 = getc(fp) << 8;
s.i16 |= getc(fp);
This code assumes that getc reads 8-bit characters, and that the data is stored most significant byte first (``big endian''). The casts to (long) ensure that the 16- and 24-bit shifts operate on long values , and the cast to (unsigned) guards against sign extension. (In general, it's safer to use all unsigned types when writing code like this,
The corresponding code to write the structure might look like:
putc(s.c, fp);
putc((unsigned)((s.i32 ^>> 24) & 0xff), fp);
putc((unsigned)((s.i32 >> 16) & 0xff), fp);
putc((unsigned)((s.i32 >> 8) & 0xff), fp);
putc((unsigned)(s.i32 & 0xff), fp);
putc((s.i16 >> 8) & 0xff, fp);
putc(s.i16 & 0xff, fp);
2015-09-18, 990👍, 0💬
Popular Posts:
What is the output of printf("%d")? 1. When we write printf("%d",x); this means compiler will print ...
What does address of operator do in background? The AddressOf operator creates a delegate object to ...
Can you explain in brief how the ASP.NET authentication process works? ASP.NET does not run by itsel...
How To Control White Spaces between Table Cells? - XHTML 1.0 Tutorials - Understanding Tables and Ta...
What is the version information in XML? “version” tag shows which version of XML is used.