User Tools

Site Tools


Synchsafe Integers

Recently, I was looking at putting together a simple, easy to use, Python library for reading and writing ID3v2 tags in mp3 files. This is rather non-trivial as the ID3v2 headers are somewhat complicated. One of the things that I found rather mystifying at first is the use of Synchsafe Integers. The Wikipedia page linked to in the previous sentence actually has a simple algorithm in C to “unsynchsafe” an integer. Nowhere, that I could find, was the reverse algorithm so I decided to publish mine here. The example on Wikipedia is in C, but I've done both of the following examples in Python (you should be able to easily adapt this back to C, or any other lang. for that matter).


The code:

def unsynchsafe(num):
    out = 0
    mask = 0x7f000000
    for i in range(4):
        out >>= 1
        out |= num & mask
        mask >>= 8
    return out


The code for the slightly more complicated makesynchsafe():

def makesynchsafe(num):
    mask = 0x0000007f
    ret = 0
    for i in range(4):
        t = num >> (i * 8)
        t &= mask
        t <<= (i * 8)
        ret |= t
        num <<= 1
    return ret
misc/synchsafe.txt · Last modified: 2009/09/28 17:38 by crustymonkey