Fast options binary trading strategies for beginners pdf22 comments
In this chapter I'll show you how to build a library that you can use to write code for reading and writing binary files. You'll use this library in Chapter 25 to write a parser for ID3 tags, the mechanism used to store metadata such as artist and album names in MP3 files. This library is also an example of how to use macros to extend the language with new constructs, turning it into a special-purpose language for solving a particular problem, in this case reading and writing binary data.
Because you'll develop the library a bit at a time, including several partial versions, it may seem you're writing a lot of code. But when all is said and done, the whole library is fewer than lines of code, and the longest macro is only 20 lines long. At a sufficiently low level of abstraction, all files are "binary" in the sense that they just contain a bunch of numbers encoded in binary form. However, it's customary to distinguish between text files , where all the numbers can be interpreted as characters representing human-readable text, and binary files , which contain data that, if interpreted as characters, yields nonprintable characters.
Binary file formats are usually designed to be both compact and efficient to parse--that's their main advantage over text-based formats. To meet both those criteria, they're usually composed of on-disk structures that are easily mapped to data structures that a program might use to represent the same data in memory. The library will give you an easy way to define the mapping between the on-disk structures defined by a binary file format and in-memory Lisp objects. Using the library, it should be easy to write a program that can read a binary file, translating it into Lisp objects that you can manipulate, and then write back out to another properly formatted binary file.
The starting point for reading and writing binary files is to open the file for reading or writing individual bytes. When you're dealing with binary files, you'll specify unsigned-byte 8. An input stream opened with such an: Above the level of individual bytes, most binary formats use a smallish number of primitive data types--numbers encoded in various ways, textual strings, bit fields, and so on--which are then composed into more complex structures.
So your first task is to define a framework for writing code to read and write the primitive data types used by a given binary format. To take a simple example, suppose you're dealing with a binary format that uses an unsigned bit integer as a primitive data type. To read such an integer, you need to read the two bytes and then combine them into a single number by multiplying one byte by , a.
For instance, assuming the binary format specifies that such bit quantities are stored in big-endian 3 form, with the most significant byte first, you can read such a number with this function:. However, Common Lisp provides a more convenient way to perform this kind of bit twiddling. The function LDB , whose name stands for load byte, can be used to extract and set with SETF any number of contiguous bits from an integer.
BYTE takes two arguments, the number of bits to extract or set and the position of the rightmost bit where the least significant bit is at position zero. LDB takes a byte specifier and the integer from which to extract the bits and returns the positive integer represented by the extracted bits. Thus, you can extract the least significant octet of an integer like this:. To write a number out as a bit integer, you need to extract the individual 8-bit bytes and write them one at a time.
To extract the individual bytes, you just need to use LDB with the same byte specifiers. Of course, you can also encode integers in many other ways--with different numbers of bytes, with different endianness, and in signed and unsigned format.
Textual strings are another kind of primitive data type you'll find in many binary formats. When you read files one byte at a time, you can't read and write strings directly--you need to decode and encode them one byte at a time, just as you do with binary-encoded numbers. And just as you can encode an integer in several ways, you can encode a string in many ways.
To start with, the binary format must specify how individual characters are encoded. To translate bytes to characters, you need to know both what character code and what character encoding you're using. A character code defines a mapping from positive integers to characters.
Each number in the mapping is called a code point. For instance, ASCII is a character code that maps the numbers from to particular characters used in the Latin alphabet. A character encoding, on the other hand, defines how the code points are represented as a sequence of bytes in a byte-oriented medium such as a file. Nearly as straightforward are pure double-byte encodings, such as UCS-2, which map between bit values and characters.
The only reason double-byte encodings can be more complex than single-byte encodings is that you may also need to know whether the bit values are supposed to be encoded in big-endian or little-endian format. Variable-width encodings use different numbers of octets for different numeric values, making them more complex but allowing them to be more compact in many cases. For instance, UTF-8, an encoding designed for use with the Unicode character code, uses a single octet to encode the values while using up to four octets to encode values up to 1,, On the other hand, texts consisting mostly of characters requiring four bytes in UTF-8 could be more compactly encoded in a straight double-byte encoding.
Common Lisp provides two functions for translating between numeric character codes and character objects: The language standard doesn't specify what character encoding an implementation must use, so there's no guarantee you can represent every character that can possibly be encoded in a given file format as a Lisp character.
In addition to specifying a character encoding, a string encoding must also specify how to encode the length of the string. Three techniques are typically used in binary file formats. The simplest is to not encode it but to let it be implicit in the position of the string in some larger structure: Both these techniques are used in ID3 tags, as you'll see in the next chapter. The other two techniques can be used to encode variable-length strings without relying on context. One is to encode the length of the string followed by the character data--the parser reads an integer value in some specified integer format and then reads that number of characters.
Another is to write the character data followed by a delimiter that can't appear in the string such as a null character. The different representations have different advantages and disadvantages, but when you're dealing with already specified binary formats, you won't have any control over which encoding is used. However, none of the encodings is particularly more difficult to read and write than any other.
To write a string back out, you just need to translate the characters back to numeric values that can be written with WRITE-BYTE and then write the null terminator after the string contents. As these examples show, the main intellectual challenge--such as it is--of reading and writing primitive elements of binary files is understanding how exactly to interpret the bytes that appear in a file and to map them to Lisp data types.
If a binary file format is well specified, this should be a straightforward proposition. Actually writing functions to read and write a particular encoding is, as they say, a simple matter of programming.
Now you can turn to the issue of reading and writing more complex on-disk structures and how to map them to Lisp objects. Since binary formats are usually used to represent data in a way that makes it easy to map to in-memory data structures, it should come as no surprise that composite on-disk structures are usually defined in ways similar to the way programming languages define in-memory structures.
Usually a composite on-disk structure will consist of a number of named parts, each of which is itself either a primitive type such as a number or a string, another composite structure, or possibly a collection of such values.
For instance, an ID3 tag defined in the 2. Following the header is a list of frames , each of which has its own internal structure. After the frames are as many null bytes as are necessary to pad the tag out to the size specified in the header. If you look at the world through the lens of object orientation, composite structures look a lot like classes.
For instance, you could write a class to represent an ID3 tag. An instance of this class would make a perfect repository to hold the data needed to represent an ID3 tag. You could then write functions to read and write instances of this class. For example, assuming the existence of certain other functions for reading the appropriate primitive data types, a read-id3-tag function might look like this:.
It's not hard to see how you could write the appropriate classes to represent all the composite data structures in a specification along with read-foo and write-foo functions for each class and for necessary primitive types.
But it's also easy to tell that all the reading and writing functions are going to be pretty similar, differing only in the specifics of what types they read and the names of the slots they store them in. It's particularly irksome when you consider that in the ID3 specification it takes about four lines of text to specify the structure of an ID3 tag, while you've already written eighteen lines of code and haven't even written write-id3-tag yet.
What you'd really like is a way to describe the structure of something like an ID3 tag in a form that's as compressed as the specification's pseudocode yet that can also be expanded into code that defines the id3-tag class and the functions that translate between bytes on disk and instances of the class. Sounds like a job for a macro. Since you already have a rough idea what code your macros will need to generate, the next step, according to the process for writing a macro I outlined in Chapter 8, is to switch perspectives and think about what a call to the macro should look like.
Since the goal is to be able to write something as compressed as the pseudocode in the ID3 specification, you can start there.
The header of an ID3 tag is specified like this:. The version consists of two bytes, the first of which--for this version of the specification--has the value 2 and the second of which--again for this version of the specification--is 0. The flags slot is eight bits, of which all but the first two are 0, and the size consists of four bytes, each of which has a 0 in the most significant bit. Some information isn't captured by this pseudocode.
For instance, exactly how the four bytes that encode the size are to be interpreted is described in a few lines of prose. Likewise, the spec describes in prose how the frame and subsequent padding is stored after this header. But most of what you need to know to be able to write code to read and write an ID3 tag is specified by this pseudocode.
Thus, you ought to be able to write an s-expression version of this pseudocode and have it expanded into the class and function definitions you'd otherwise have to write by hand--something, perhaps, like this:.
Since this is just a bit of fantasizing, you don't have to worry about exactly how the macro define-binary-class will know what to do with expressions such as isostring: Okay, enough fantasizing about good-looking code; now you need to get to work writing define-binary-class --writing the code that will turn that concise expression of what an ID3 tag looks like into code that can represent one in memory, read one off disk, and write it back out.
To start with, you should define a package for this library. Here's the package file that comes with the version you can download from the book's Web site:.
Since you already have a handwritten version of the code you want to generate, it shouldn't be too hard to write such a macro.
If you look back at the define-binary-class form, you'll see that it takes two arguments, the name id3-tag and a list of slot specifiers, each of which is itself a two-item list. A single slot specifier from define-binary-class looks something like this:.
Instead, you need something like this:. First define a simple function to translate a symbol to the corresponding keyword symbol. The result, slightly reformatted here for better readability, should look familiar since it's exactly the class definition you wrote by hand earlier:. Next you need to make define-binary-class also generate a function that can read an instance of the new class.
Looking back at the read-id3-tag function you wrote before, this seems a bit trickier, as the read-id3-tag wasn't quite so regular--to read each slot's value, you had to call a different function.
Not to mention, the name of the function, read-id3-tag , while derived from the name of the class you're defining, isn't one of the arguments to define-binary-class and thus isn't available to be interpolated into a template the way the class name was.
You could deal with both of those problems by devising and following a naming convention so the macro can figure out the name of the function to call based on the name of the type in the slot specifier. However, this would require define-binary-class to generate the name read-id3-tag , which is possible but a bad idea.
Macros that create global definitions should generally use only names passed to them by their callers; macros that generate names under the covers can cause hard-to-predict--and hard-to-debug--name conflicts when the generated names happen to be the same as names used elsewhere. You can avoid both these inconveniences by noticing that all the functions that read a particular type of value have the same fundamental purpose, to read a value of a specific type from a stream.