Encode a simple integer. Integers are encoded as a simple base-256 byte sequence, most significant byte first, prefixed with a length byte. In principle we support arbitrary integer sizes, in practice Javascript doesn't even **have** integers so some precision might get lost.
function encodeIntegerish(val, type) {
    var i, arr, buf;

    // Get the bytes that we're going to encode.
    arr = intArray(val);

    // Now that we know the length, we allocate a buffer of the required size.
    // We set the type and length bytes appropriately.
    buf = new Buffer(2 + arr.length);
    buf[0] = type;
    buf[1] = arr.length;

    // Copy the bytes into the array.
    for (i = 0; i < arr.length; i++) {
        buf[i + 2] = arr[i];
    }

    return buf;
}