1 ################################################################################
3 # Copyright (C) 2002-2005 Travis Shirk <travis@pobox.com>
4 # Copyright (C) 2001 Ryan Finne <ryan@finnie.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 ################################################################################
22 # Accepts a string of bytes (chars) and returns an array of bits
23 # representing the bytes in big endian byte (Most significant byte/bit first)
24 # order. Each byte can have it's higher bits ignored by passing an sz arg.
25 def bytes2bin(bytes
, sz
= 8):
27 raise ValueError("Invalid sz value: " + str(sz
));
38 bits
.extend([0] * (sz
- len(bits
)));
42 # Big endian byte order.
50 # Convert am array of bits (MSB first) into a string of characters.
78 # Convert and array of "bits" (MSB first) to it's decimal value.
91 def bytes2dec(bytes
, sz
= 8):
92 return bin2dec(bytes2bin(bytes
, sz
));
94 # Convert a decimal value to an array of bits (MSB first), optionally
95 # padding the overall size to p bits.
96 def dec2bin(n
, p
= 0):
101 retVal
.append(n
& 1);
105 retVal
.extend([0] * (p
- len(retVal
)));
109 def dec2bytes(n
, p
= 0):
110 return bin2bytes(dec2bin(n
, p
));
112 # Convert a list of bits (MSB first) to a synch safe list of bits (section 6.2
113 # of the ID3 2.4 spec).
114 def bin2synchsafe(x
):
115 if len(x
) > 32 or bin2dec(x
) > 268435456: # 2^28
116 raise ValueError("Invalid value");
122 bites
+= chr((n
>> 21) & 0x7f);
123 bites
+= chr((n
>> 14) & 0x7f);
124 bites
+= chr((n
>> 7) & 0x7f);
125 bites
+= chr((n
>> 0) & 0x7f);
126 bits
= bytes2bin(bites
);
128 bits
= ([0] * (32 - len(x
))) + bits
;
132 def bytes2str(bytes
):
135 s
+= ("\\x%02x" % ord(b
))