Skip to content

Instantly share code, notes, and snippets.

@DanielKeep
Created May 3, 2012 11:24
Show Gist options
  • Save DanielKeep/2585085 to your computer and use it in GitHub Desktop.
Save DanielKeep/2585085 to your computer and use it in GitHub Desktop.
Binary Image Exchange Format Proposal

Binary Image Exchange Format Proposal

Author: Daniel Keep <[email protected]>
Version: 1.0.3
Licence:http://creativecommons.org/publicdomain/zero/1.0/
Discussion:http://www.reddit.com/r/dcpu16/comments/t4xy2/

Recently, I've been working on some tools for creating disk images and formatting said images with a filesystem. At the same time, there have been a number of people on Reddit asking about what byte order their tools should be producing or consuming. It's also occurred to me that DCPU is a bit unusual among emulated platforms in that some of the most prominent emulators right from the get-go are actually web apps that users copy+paste programs into.

When I wrote up my floppy drive spec, I wanted to include a sample program with a corresponding disk image. Sadly, I couldn't attach a binary file, only text. It occurrs to me that web-based emulators could very well have similar problems.

So, rather than get ahead of myself, I'd like to make a proposal and see how the community responds. Specifically, I'm looking for the opinions of tool writers.

The idea

I'm proposing that we define a very simple encapsulation format to be used for storing and exchanging binary files of various types. Specifically, binary dumps (or images) of data comprised of 16-bit words for the DCPU-16, representing data such as machine code, ROM and disk images.

As an example, here is an image of a 1.44 MB disk formatted with zeroes and the LE-packed string "Hello, World!" stored at the beginning:

BIEF/0.1
Type: Floppy
Access: Read-Write
Compression: Zlib
Encoding: Base64
Payload-Length: 2010

eNrtwTENACAMALBJgR8hOMAAfEuW4P/ABGfbMzNHrXZrZ/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPnq4MQRq

In addition to the basic encapsulation headers (Byte-Order, Compression, Encoding and Content-Length) it also allows for special-purpose headers to be added (Access and Type).

Benefits and drawbacks

Things this format will give us:

  • A common format for binary image interchange that also specifies byte order.
  • A format with built-in compression, making internet transmission quicker.
  • A format which can be stored as plain text, suitable for submission to web apps and paste bins without risk of corruption.
  • A format which should be trivially readable in just about every programming language in the world [1].

Drawbacks:

  • Not as simple to read as an uncompressed, unencoded fixed byte order image.
  • Necessarily larger if files are stored without compression.

Open questions

  • Is it worth having a little-endian mode at all? It's still in the reference implementation, but I've removed it from the spec because I just can't come up with a logically sound reason for having it.
  • Is Content-Length worth having, or just throw it away. It feels a bit like a security blanket: makes you feel better but doesn't really do anything.

Specifics

No file extension is specified or required.

Each conforming file begins with the format identifier. This is the five characters "BIEF/" followed by a version identifier and terminated by a single newline. The version number described in this proposal is "0.1"; it will be changed to "1.0" in the event the format is accepted by the community.

Newlines may be either a single linefeed (0x0a) byte or a carriage-return, linefeed (0x0d, 0x0a) byte sequence. Newlines should be written out as a carriage-return, lifefeed sequence where possible [4].

This is followed by a sequence of zero or more headers. Each header is made up of a key, followed by a colon (':'), followed by the value and finally terminated by a newline character. Unless there is a compelling reason to do so, keys and values should both the case insensitive. Whitespace around the key and value should be ignored. Headers should be written in 7-bit ASCII, but read in as UTF-8 if possible [2].

Malformed or unrecognised headers should be ignored. It is entirely possible for the file to contain no headers at all. In the case of duplicate headers, the last value for a given header is used.

The headers are terminated by a zero-length line; that is, two consecutive newlines. If a file contains no headers, then it will start with a newline.

At this point, the rest of the file is the actual payload (or data) of the file. The file should not contain any trailing bytes.

General headers

Byte-Order

Deprecated. This header is no longer a part of the base format. It will remain documented, however, until the format is accepted and finalised.

"Big-Endian" or "Little-Endian", default if not specified is big-endian.

Producing programs should endeavour to output files using big-endian by default.

Encoding

"None" or "Base64", default if not specified is None.

Producing programs should endeavour to output files using Base64 by default.

The use of base64 allows for images to be passed around on the internet more easily: they can be put into gists or uploaded to pastebins. This also avoids any potential problems with languages that represent binary data as Unicode or encoded 8-bit strings (like Javascript), and languages without 8-bit safe strings (which I believe Lua is an example of).

Compression

"None" or "Zlib", default if not specified is None.

Producing programs should endeavour to output files using Zlib by default.

Compression means a 1.44 MB disk image starting with "Hello, World!" is just over 2 KB instead of 1.44 MB.

zlib was chosen thanks to its near total ubiquity. Specifically, it means a deflate-compressed stream with the zlib header, not a raw deflate stream as Microsoft seems to love to use [3].

Payload-Length

The value is a decimal integer representing the number of compressed, encoded bytes in the payload.

Producing programs should include a Payload-Length header, consuming programs should ideally be prepared to operate without one.

This header is included largely as a hedge against pastebins tacking on an errant newline here or there in the face of a particularly inflexible base64 implementation.

Disk image headers

This section is just normative; that is, I'm not attempting to standardise this stuff, just giving a little extra context on what I'm personally using this for.

Type
Specifies the type of media the image represents. Currently, I'm only using "Floppy", although I can see "Tape" and "Hard-Disk" being used in the future.
Access
"Read-Write" or "Read-Only". Used to implement the write-lock switch on the old 3.5" floppy.

Changelog

1.0.3

Changed proposal to be conforming reST. Added identification line. The major impetus for this was to allow the reference implementation to automatically fall back to raw mode if the line isn't present.

Changed byte-order default to big-endian then proceeded to remove it from the spec entirely. Most people seem to have settled on big-endian already, as much as I think that's a completely silly choice. As Harold Lam would say: I'm a big enough man to admit when you're all bloody wrong. :P

1.0.2

Added license. Added language on default newline format for output. Clarified behaviour on reading duplicate headers. Added changelog. Added link back to Reddit discussion thread.

Clarified that this is for memory images, not bitmap images.

Renamed "Content-Length" to "Payload-Length"; kudos to cheese_magnet.

1.0.1
Fixed a mistake in the example disk image.
1.0.0
Initial release.

License

Licensed under the CC0 license: http://creativecommons.org/publicdomain/zero/1.0/

To the extent possible under law, the author has waived all copyright and related or neighboring rights to "Binary Image Exchange Format Proposal". This work is published from: Australia.

[1]Show me a language without good line-reading IO routines in its standard library, and I'll show you a rubbish language. ;)
[2]This is the "generous on input, strict on output" principle.
[3]Incidentally, don't use System.IO.Compression.DeflateStream. It's complete garbage.
[4]This has been chosen because the most common text editor in the world is, probably (and unfortunately), Microsoft Notepad. Notepad is also just about the only text editor left that refuses to recognise single linefeeds as newlines. In this way, BIEF files opened in Notepad will not look "broken" to lay people.
/*
* Binary Image Exchange Format reference implementation.
*
* Note that not everything here has been exhaustively tested. There may be
* bugs a-lurkin'.
*
* This implementation is written to conform to version 1.0.3 of the BIEF spec.
*
* Latest version:
* https://gist.github.com/2585085
*
* Authors:
* Daniel Keep <[email protected]>.
*
* History:
* v1.1: Christened format "BIEF". Changed to big-endian by default.
* ReadImage now detects non-BIEF files and reads them as big-endian
* raw files instead.
* v1.0: First release.
*/
/*
* Copyright (c) 2012 Daniel Keep.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
// NuGet Package: DotNetZip
using Ionic.Zlib;
namespace Dk.x10c
{
/// <summary>
/// This class has methods for reading and writing BIEF
/// format files, as specified by <https://gist.github.com/2585085>.
/// </summary>
public static class BinaryImage
{
/// <summary>
/// Reads a binary image. Note that this method will work on both
/// actual BIEF-formatted files and raw big-endian files.
/// </summary>
/// <param name="path">Path to the binary image file.</param>
/// <param name="headers">If non-null, all headers will be
/// added to this dictionary. Header keys will be lower case.</param>
/// <returns>The decoded image data.</returns>
public static ushort[] ReadImage(string path, Dictionary<string, string> headers = null)
{
using (var fs = new FileStream(path, FileMode.Open))
return ReadImage(fs, headers);
}
/// <summary>
/// Reads a binary image. Note that this method will work on both
/// actual BIEF-formatted files and raw big-endian files.
/// </summary>
/// <param name="s">Stream to read from. The stream must be seekable.</param>
/// <param name="headers">If non-null, all headers will be
/// added to this dictionary. Header keys will be lower case.</param>
/// <returns>The decoded image data.</returns>
public static ushort[] ReadImage(Stream s, Dictionary<string, string> headers = null)
{
// Defaults as per spec
var byteOrder = ByteOrder.BigEndian;
var compress = Compression.None;
var encoding = Encoding.None;
var payLength = -1;
// Mark current position
var headerStart = s.Seek(0, SeekOrigin.Current);
// Parse headers
var tr = new StreamReader(s, System.Text.Encoding.UTF8);
{
string line = tr.ReadLine();
{
var parts = line.Split(verSep, 2, StringSplitOptions.None);
if (parts.Length == 2 && parts[0] == "BIEF")
{
// Only version 0.1 supported.
if (parts[1] != "0.1")
throw new Exception("Unsupported version of BIEF: " + parts[1]);
}
else
{
// Ok, this means the file isn't BIEF. Try to read
// as big-endian, uncompressed raw.
s.Seek(headerStart, SeekOrigin.Begin);
return ReadRawImage(s);
}
}
while ((line = tr.ReadLine()) != null)
{
line = line.Trim();
if (line.Length == 0)
// No more headers!
break;
var parts = line.Split(headerSep, 2, StringSplitOptions.None);
// We ignore lines not of the form "key: value".
if (parts.Length == 2)
{
var key = parts[0].Trim().ToLower();
var val = parts[1].Trim();
// Note that this includes standard headers, since users
// might be curious.
if (headers != null)
headers.Add(key, val);
switch (key)
{
case "byte-order":
switch (val.ToLower())
{
case "big-endian":
byteOrder = ByteOrder.BigEndian;
break;
case "little-endian":
byteOrder = ByteOrder.LittleEndian;
break;
}
break;
case "compression":
switch (val.ToLower())
{
case "none":
compress = Compression.None;
break;
case "zlib":
compress = Compression.Zlib;
break;
}
break;
case "encoding":
switch (val.ToLower())
{
case "none":
encoding = Encoding.None;
break;
case "base64":
encoding = Encoding.Base64;
break;
}
break;
case "payload-length":
if (!int.TryParse(val, out payLength))
payLength = -1;
break;
}
}
}
}
// Locate end of headers.
/*
* This is nasty because StreamReader doesn't deign to tell us
* how many bytes its consumed and it buffers. This means that
* once we've read the headers, we don't *actually* know where in
* the file we're supposed to be.
*
* Outside of re-writing the header parsing code to avoid the use
* of StreamReader entirely (*effort*), this is the next-best
* solution I could think of.
*
* All we do is scan the stream, looking for two consecutive new
* lines. gotEol is initialised to true so that if the first
* thing we see is a newline (i.e. no headers at all), we take
* that as the end of the headers.
*/
s.Seek(headerStart, SeekOrigin.Begin);
long dataStart = 0;
{
int b;
bool gotEol = true,
gotCr = false;
while ((b = s.ReadByte()) >= 0)
{
var c = (char)b;
if (gotCr)
{
gotCr = false;
if (c == '\n')
{
if (gotEol)
break;
gotEol = true;
}
else
gotEol = false;
}
else if (b == '\n')
{
if (gotEol)
break;
gotEol = true;
}
else if (b == '\r')
{
gotCr = true;
}
else
gotEol = false;
}
dataStart = s.Seek(0, SeekOrigin.Current);
}
// Compute payload length if not specified.
if (payLength < 0)
{
payLength = (int)(s.Seek(0, SeekOrigin.End) - dataStart);
s.Seek(dataStart, SeekOrigin.Begin);
}
// Ensure we're at the start of the payload
s.Seek(dataStart, SeekOrigin.Begin);
// Read in the (potentially) encoded data
var ebytes = new byte[payLength];
s.Read(ebytes, 0, payLength);
// Handle decoding to (potentially) compressed bytes.
byte[] cbytes;
switch (encoding)
{
case Encoding.None:
cbytes = ebytes;
break;
case Encoding.Base64:
{
var str = System.Text.Encoding.UTF8.GetString(ebytes);
cbytes = Convert.FromBase64String(str);
}
break;
default:
throw new NotImplementedException("unknown encoding");
}
// Handle decompressing to bytes.
byte[] bytes;
switch (compress)
{
case Compression.None:
bytes = cbytes;
break;
case Compression.Zlib:
bytes = zlibDecompress(cbytes);
break;
default:
throw new NotImplementedException("unknown compression");
}
// Ensure we have complete words.
if ((bytes.Length & 1) == 1)
throw new InvalidDataException("malformed binary image: last word is incomplete");
// Convert to words.
var words = new ushort[bytes.Length >> 1];
{
int lb, hb;
switch (byteOrder)
{
case ByteOrder.BigEndian:
hb = 0;
lb = 1;
break;
case ByteOrder.LittleEndian:
lb = 0;
hb = 1;
break;
default:
// What, seriously?!
throw new NotImplementedException("unknown byte order");
}
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
words[i] = (ushort)(bytes[j + lb] | (bytes[j + hb] << 8));
}
}
return words;
}
/// <summary>
/// Writes data to a binary image.
/// </summary>
/// <param name="path">Path of the file to write to.</param>
/// <param name="words">The data to write.</param>
/// <param name="headers">Additional headers to include in the output.</param>
/// <param name="compression">Compression scheme to use.</param>
/// <param name="encoding">Byte encoding scheme to use.</param>
/// <param name="byteOrder">On-disk byte ordering.</param>
public static void WriteImage(string path,
ushort[] words,
Dictionary<string, string> headers = null,
Compression compression = Compression.Zlib,
Encoding encoding = Encoding.Base64,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
using (var fs = new FileStream(path, FileMode.Create))
WriteImage(fs, words, headers, compression, encoding, byteOrder);
}
/// <summary>
/// Writes data to a binary image.
/// </summary>
/// <param name="s">Stream to write to.</param>
/// <param name="words">The data to write.</param>
/// <param name="headers">Additional headers to include in the output.</param>
/// <param name="compression">Compression scheme to use.</param>
/// <param name="encoding">Byte encoding scheme to use.</param>
/// <param name="byteOrder">On-disk byte ordering.</param>
public static void WriteImage(
Stream s,
ushort[] words,
Dictionary<string, string> headers = null,
Compression compression = Compression.Zlib,
Encoding encoding = Encoding.Base64,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
// What will eventually contain our encoded bytes.
byte[] ebytes;
// Write out headers.
/* NOTE: we can't dispose this since it also disposes the
* underlying stream. How *thoughtful*.
*/
var tw = new StreamWriter(s, System.Text.Encoding.ASCII);
{
tw.NewLine = "\r\n";
tw.WriteLine("BIEF/0.1");
// Write out extra headers. If these include standard headers,
// it won't matter because we'll supercede them.
if (headers != null)
foreach (var kv in headers)
tw.WriteLine("{0}: {1}", kv.Key, kv.Value);
int lb, hb;
switch (byteOrder)
{
case ByteOrder.BigEndian:
// Don't output an explicit header for this case.
//tw.WriteLine("Byte-Order: Big-Endian");
hb = 0;
lb = 1;
break;
case ByteOrder.LittleEndian:
tw.WriteLine("Byte-Order: Little-Endian");
lb = 0;
hb = 1;
break;
default:
// WAT.
throw new NotImplementedException("unknown byte order");
}
// Convert words into byte-ordered bytes.
var bytes = new byte[2 * words.Length];
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
bytes[j + lb] = (byte)words[i];
bytes[j + hb] = (byte)(words[i] >> 8);
}
// Compress
byte[] cbytes;
switch (compression)
{
case Compression.None:
// Default
//tw.WriteLine("Compression: None");
cbytes = bytes;
break;
case Compression.Zlib:
tw.WriteLine("Compression: Zlib");
cbytes = zlibCompress(bytes);
break;
default:
throw new NotImplementedException("unknown compression");
}
// Encode
switch (encoding)
{
case Encoding.None:
// Default.
//tw.WriteLine("Encoding: None");
ebytes = cbytes;
break;
case Encoding.Base64:
tw.WriteLine("Encoding: Base64");
{
var str = Convert.ToBase64String(cbytes, Base64FormattingOptions.InsertLineBreaks);
ebytes = System.Text.Encoding.ASCII.GetBytes(str);
}
break;
default:
throw new NotImplementedException("unknown encoding");
}
// Output payload-length header.
tw.WriteLine("Payload-Length: {0}", ebytes.Length);
// Terminate headers
tw.WriteLine();
tw.Flush();
}
// Write encoded bytes out; and we're done!
s.Write(ebytes, 0, ebytes.Length);
}
/// <summary>
/// Reads a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="path">Path to the file to read from.</param>
/// <param name="byteOrder">Byte order of the file.</param>
/// <returns>The contents of the file.</returns>
public static ushort[] ReadRawImage(
string path,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
using (var fs = new FileStream(path, FileMode.Open))
return ReadRawImage(fs, byteOrder);
}
/// <summary>
/// Reads a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="s">Stream to read from.</param>
/// <param name="byteOrder">Byte order of the file.</param>
/// <returns>The contents of the file.</returns>
public static ushort[] ReadRawImage(
Stream s,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
var start = s.Seek(0, SeekOrigin.Current);
var end = s.Seek(0, SeekOrigin.End);
s.Seek(start, SeekOrigin.Begin);
var length = (int)(end - start);
if ((length & 1) == 1)
throw new InvalidDataException("malformed binary image: last word is incomplete");
var bytes = new byte[length];
s.Read(bytes, 0, length);
var words = new ushort[length >> 1];
int lb, hb;
if (byteOrder == ByteOrder.LittleEndian)
{
lb = 0;
hb = 1;
}
else
{
hb = 0;
lb = 1;
}
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
words[i] = (ushort)(bytes[j + lb] | (bytes[j + hb] << 8));
}
return words;
}
/// <summary>
/// Writes a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="path">Path to the file to write to.</param>
/// <param name="words">Data to write.</param>
/// <param name="byteOrder">Byte order of the file.</param>
public static void WriteRawImage(
string path,
ushort[] words,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
using (var fs = new FileStream(path, FileMode.Create))
WriteRawImage(fs, words, byteOrder);
}
/// <summary>
/// Writes a raw, unencapsulated binary image, performing byte swapping
/// as necessary.
/// </summary>
/// <param name="s">Stream to write to.</param>
/// <param name="words">Data to write.</param>
/// <param name="byteOrder">Byte order of the file.</param>
public static void WriteRawImage(
Stream s,
ushort[] words,
ByteOrder byteOrder = ByteOrder.BigEndian)
{
var bytes = new byte[words.Length << 1];
int lb, hb;
if (byteOrder == ByteOrder.LittleEndian)
{
lb = 0;
hb = 1;
}
else
{
hb = 0;
lb = 1;
}
for (int i = 0, j = 0;
i < words.Length;
++i, j += 2)
{
bytes[j + lb] = (byte)words[i];
bytes[j + hb] = (byte)(words[i] >> 8);
}
s.Write(bytes, 0, bytes.Length);
}
private static byte[] zlibCompress(byte[] bytes)
{
return ZlibStream.CompressBuffer(bytes);
}
private static byte[] zlibDecompress(byte[] cbytes)
{
return ZlibStream.UncompressBuffer(cbytes);
}
static BinaryImage()
{
verSep = new char[] { '/' };
headerSep = new char[] { ':' };
}
private static readonly char[] verSep;
private static readonly char[] headerSep;
}
public enum ByteOrder
{
BigEndian,
LittleEndian,
}
public enum Encoding
{
None,
Base64,
}
public enum Compression
{
None,
Zlib,
}
}
@jonpovey
Copy link

jonpovey commented May 3, 2012

This is not shit.

@DanielKeep
Copy link
Author

jonpovey: I try :)

@rustyoz
Copy link

rustyoz commented May 28, 2012

any chances of creating creating a tool to convert disks from compressed to uncompressed?

i've been trying to get devkit to use uncompressed disks by changing the default settings in read and write image, doesn't work though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment