user621989
user621989

Reputation:

Encoding and decoding synchsafe integers

What is the best way to encode and decode synchsafe integers?


A synchsafe integer (used in ID3v2 tags) is one in which the most significant bit is always 0 and is disregarded.

For example, 11111111 (255) as a synchsafe integer is 00000001 01111111 (383); and 11111111 11111111 is equivalent to a synchsafe 00000011 01111111 01111111.

Upvotes: 0

Views: 865

Answers (2)

steven smith
steven smith

Reputation: 1577

The solution on wikipedia seems to have been edited out. The concept is simple. the synchsafe value is an array of bytes with the most significant bit masked out then shifted by 7.

I needed the functionality so I wrote this kotlin function to convert s byte array into a long. ID3V2 also has a checksum that uses 5 bytes so the array size determines the output. I check to make sure all the bytes in are valid for synch-safe and throw an exception if any are not. I don't check for overflow.

private fun ByteArray.getSyncSafe() : Long {
    var rv = 0L
    if (any{0x80 and it.toInt() != 0})
        throw RuntimeException("TAG: ${this.map{
            "0x%02x".format(it.toInt())
        }}: Bad synchsafe array.")
    map{rv = rv.shl(8) + it.toLong()}
    return rv
}

Upvotes: 0

samplebias
samplebias

Reputation: 37919

Solution is available on Wikipedia synchsafe page.

Upvotes: 1

Related Questions