Bit Simulator - Data Serialization
Andrew Polk  •  July 1, 2020  •  C#, Unity3D

The Problem

When creating something as complex as a logic simulator you're going to want to eventually save the design of your circuit and hopefully the state too. When creating the individual gates and chips I opted to use BitArrays which act similar to arrays of booleans but have the added advantage of being able to perform bitwise operations directly on the objects them selves.

The two core components/objects gates and chips both use BitArrays to store the input values. In addition chips have a second BitArray to store the output since a chip can have multiple outputs vs a gate which only has one. When saving the state of the simulation it is enough to save the BitArray state, the connections between chips/gates and the component update queue (What component should have it's output updated next).

Now comes the problem with this approach, there is no direct converter from a BitArray to JSON. Which is why we'll we creating our own.

The Converter

To create a JSON converter we'll start off with a new class that extends JsonConverter, extending this class requires us to override three methods.

  • CanConvert
  • WriteJson
  • ReadJson

This first method is simple, we just need to return true if the object type passed in is the type we want to convert with this class, BitArray in this case.

Next we'll want to override the WriteJson method. Now this is where we have a little more freedom to decide how we want to implement it. We need to either transform the object into a string or some other object that can be serialized. I have opted to transform it into a bit string of the form "0011011101" so that if I need to modify the json files while testing it's in a format that I can understand. There are other options that work also such as converting it into bytes which takes up the smallest amount of space but is not as readable and may require extra information such as how many bits are in the array. Hex representations are another option.

To aid in creating this helper method I added a BitArray extension method which can be called on the object itself and loops through the array building a string of 1s and 0s

Finally we need to override the ReadJson method, this will pass in the JSON string/object and expects a BitArray object to be returned. For this method I create a new boolean array of the correct lenght and then iterate over the json string updating the boolean at each position. Once the boolean array is correct I created a new BitArray object with the boolean array passed into the constructor.


Using the Converter

Implementing the encoder is as simple as adding the new BitArrayConverter class to the JsonSerializer options used when saving and loading.


Related Project

© 2019 Andrew Polk