Issue
I'm having trouble parsing the key signature of a MIDI file. the time signature should be in the form ff 59 02 sf mi
. The official MIDI documentation says that sf
should be a value between 7 and -7, while mi
is either 0 or 1. I am assuming when sf
is negative it is stored using two's complement, but how do I know when the value I am reading is in two's complement or not?
Solution
It seems likely to me that, if the byte is stored in two's complement when negative, it is also stored in twos complement when positive. One of the selling points of two's complement is that the representation of positive values are identical to their unsigned binary counterpart. For example, 0001
is +1 in either representation. This means that it doesn't really make sense for a data format to alternate between two's complement and unsigned binary depending on whether the value is positive.
If you're wondering if there's an easy way of turning two's-complement-encoded bytes into signed integer values, you can use the struct
module for that.
>>> import struct
>>> data = bytes([0xff, 0x59, 0x02, 0xf9, 0x01])
>>> struct.unpack("xxxbb", data)
(-7, 1)
The "xxxbb" value here indicates that the first three bytes should be ignored, and the next two bytes are signed numbers taking up 8 bits each.
It's also possible to unpack data stored in a list of strings this way, via an intermediary conversion to bytes:
import struct
data = ["ff", "59", "02", "f9", "01"]
data = bytes(int(x, 16) for x in data)
print(struct.unpack("xxxbb", data))
Answered By - Kevin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.