1 #!/usr/bin/env python 2 3 """ 4 Variable-length integer functions. 5 6 Copyright (C) 2009 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along 18 with this program. If not, see <http://www.gnu.org/licenses/>. 19 """ 20 21 try: 22 from vint import vint as _vint 23 24 def vint(number): 25 26 "Write 'number' as a variable-length integer." 27 28 if number >= 0: 29 return _vint(number) 30 else: 31 raise ValueError, "Number %r is negative." % number 32 33 except ImportError: 34 35 def vint(number): 36 37 "Write 'number' as a variable-length integer." 38 39 if number >= 0: 40 41 # Special case: one byte containing a 7-bit number. 42 43 if number < 128: 44 return chr(number) 45 46 # Write the number from least to most significant digits. 47 48 bytes = [] 49 50 while number != 0: 51 lsd = number & 127 52 number = number >> 7 53 if number != 0: 54 lsd |= 128 55 bytes.append(chr(lsd)) 56 57 return "".join(bytes) 58 59 # Negative numbers are not supported. 60 61 else: 62 raise ValueError, "Number %r is negative." % number 63 64 # vim: tabstop=4 expandtab shiftwidth=4