1 #!/usr/bin/env python 2 3 """ 4 Character-related functions. 5 6 Copyright (C) 2015, 2016 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 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from native import str_ord 23 24 def chr(i): pass 25 26 _hexdigits = "0123456789abcdef" 27 28 def _base(number, base, prefix=""): 29 30 """ 31 Return 'number' encoded in the given 'base', prefixed with 'prefix'. 32 """ 33 34 if number < 0: 35 number = -number 36 sign = "-" 37 else: 38 sign = "" 39 40 digits = [] 41 42 while number: 43 digits.append(_hexdigits[number % base]) 44 number = number / base 45 46 digits.append(prefix) 47 48 if sign: 49 digits.append(sign) 50 51 return "".join(reversed(digits)) 52 53 def hex(number, prefix="0x"): 54 55 """ 56 Return 'number' encoded as a hexadecimal (base 16) value, prefixed with 57 'prefix' ("0x" by default). 58 """ 59 60 return _base(number, 16, prefix) 61 62 def oct(number, prefix="0"): 63 64 """ 65 Return 'number' encoded as an octal (base 8) value, prefixed with 'prefix' 66 ("0" by default). 67 """ 68 69 return _base(number, 8, prefix) 70 71 def ord(c): 72 73 "Return the value of the given character 'c'." 74 75 if isinstance(c, string) and len(c) == 1: 76 return str_ord(c.__data__) 77 else: 78 raise ValueError(c) 79 80 def unichr(i): pass 81 82 # vim: tabstop=4 expandtab shiftwidth=4