Fix length calculation when encoding as binary