1 #!/usr/bin/env python 2 3 """ 4 Character-related functions. 5 6 Copyright (C) 2015, 2016, 2017 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 if number: 43 while number: 44 digits.append(_hexdigits[number % base]) 45 number = number / base 46 else: 47 digits.append("0") 48 49 digits.append(prefix) 50 51 if sign: 52 digits.append(sign) 53 54 return "".join(reversed(digits)) 55 56 def hex(number, prefix="0x"): 57 58 """ 59 Return 'number' encoded as a hexadecimal (base 16) value, prefixed with 60 'prefix' ("0x" by default). 61 """ 62 63 return _base(number, 16, prefix) 64 65 def oct(number, prefix="0"): 66 67 """ 68 Return 'number' encoded as an octal (base 8) value, prefixed with 'prefix' 69 ("0" by default). 70 """ 71 72 return _base(number, 8, prefix) 73 74 def ord(c): 75 76 "Return the value of the given character 'c'." 77 78 if isinstance(c, string) and len(c) == 1: 79 return str_ord(c.__data__) 80 else: 81 raise ValueError(c) 82 83 def unichr(i): pass 84 85 # vim: tabstop=4 expandtab shiftwidth=4