query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
convert decimal to hex
python
def _hex_to_dec(ip, check=True): """Hexadecimal to decimal conversion.""" if check and not is_hex(ip): raise ValueError('_hex_to_dec: invalid IP: "%s"' % ip) if isinstance(ip, int): ip = hex(ip) return int(str(ip), 16)
https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L251-L257
convert decimal to hex
python
def _convert_hex_str_to_int(val): """Convert hexadecimal formatted ids to signed int64""" if val is None: return None hex_num = int(val, 16) # ensure it fits into 64-bit if hex_num > 0x7FFFFFFFFFFFFFFF: hex_num -= 0x10000000000000000 assert -9223372036854775808 <= hex_num <= 9223372036854775807 return hex_num
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L247-L258
convert decimal to hex
python
def num2hex(self, num): ''' Convert a decimal number to hexadecimal ''' temp = '' for i in range(0, 4): x = self.hexChars[ ( num >> (i * 8 + 4) ) & 0x0F ] y = self.hexChars[ ( num >> (i * 8) ) & 0x0F ] temp += (x + y) return temp
https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/EAHashingAlgorithm.py#L26-L36
convert decimal to hex
python
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L38-L48
convert decimal to hex
python
def toHex(val): """Converts the given value (0-255) into its hexadecimal representation""" hex = "0123456789abcdef" return hex[int(val / 16)] + hex[int(val - int(val / 16) * 16)]
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/visualization/helpers.py#L286-L289
convert decimal to hex
python
def _decimal_to_xsd_format(value): """ Converts a decimal.Decimal value to its XSD decimal type value. Result is a string containing the XSD decimal type's lexical value representation. The conversion is done without any precision loss. Note that Python's native decimal.Decimal string representation will not do here as the lexical representation desired here does not allow representing decimal values using float-like `<mantissa>E<exponent>' format, e.g. 12E+30 or 0.10006E-12. """ value = XDecimal._decimal_canonical(value) negative, digits, exponent = value.as_tuple() # The following implementation assumes the following tuple decimal # encoding (part of the canonical decimal value encoding): # - digits must contain at least one element # - no leading integral 0 digits except a single one in 0 (if a non-0 # decimal value has leading integral 0 digits they must be encoded # in its 'exponent' value and not included explicitly in its # 'digits' tuple) assert digits assert digits[0] != 0 or len(digits) == 1 result = [] if negative: result.append("-") # No fractional digits. if exponent >= 0: result.extend(str(x) for x in digits) result.extend("0" * exponent) return "".join(result) digit_count = len(digits) # Decimal point offset from the given digit start. point_offset = digit_count + exponent # Trim trailing fractional 0 digits. fractional_digit_count = min(digit_count, -exponent) while fractional_digit_count and digits[digit_count - 1] == 0: digit_count -= 1 fractional_digit_count -= 1 # No trailing fractional 0 digits and a decimal point coming not after # the given digits, meaning there is no need to add additional trailing # integral 0 digits. if point_offset <= 0: # No integral digits. result.append("0") if digit_count > 0: result.append(".") result.append("0" * -point_offset) result.extend(str(x) for x in digits[:digit_count]) else: # Have integral and possibly some fractional digits. result.extend(str(x) for x in digits[:point_offset]) if point_offset < digit_count: result.append(".") result.extend(str(x) for x in digits[point_offset:digit_count]) return "".join(result)
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbuiltin.py#L129-L192
convert decimal to hex
python
def _oct_to_dec(ip, check=True): """Octal to decimal conversion.""" if check and not is_oct(ip): raise ValueError('_oct_to_dec: invalid IP: "%s"' % ip) if isinstance(ip, int): ip = oct(ip) return int(str(ip), 8)
https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L265-L271
convert decimal to hex
python
def toFloat(val): """Converts the given value (0-255) into its hexadecimal representation""" hex = "0123456789abcdef" return float(hex.find(val[0]) * 16 + hex.find(val[1]))
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/visualization/helpers.py#L292-L295
convert decimal to hex
python
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): return value try: return decimal.Decimal(value) except Exception as e: raise ValueError(str(e))
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L77-L89
convert decimal to hex
python
def to_decimal(value, ctx): """ Tries conversion of any value to a decimal """ if isinstance(value, bool): return Decimal(1) if value else Decimal(0) elif isinstance(value, int): return Decimal(value) elif isinstance(value, Decimal): return value elif isinstance(value, str): try: return Decimal(value) except Exception: pass raise EvaluationError("Can't convert '%s' to a decimal" % str(value))
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L53-L69
convert decimal to hex
python
def float2dec(ft, decimal_digits): """ Convert float (or int) to Decimal (rounding up) with the requested number of decimal digits. Arguments: ft (float, int): Number to convert decimal (int): Number of digits after decimal point Return: Decimal: Number converted to decima """ with decimal.localcontext() as ctx: ctx.rounding = decimal.ROUND_UP places = decimal.Decimal(10)**(-decimal_digits) return decimal.Decimal.from_float(float(ft)).quantize(places)
https://github.com/secnot/rectpack/blob/21d46be48fd453500ea49de699bc9eabc427bdf7/rectpack/packer.py#L10-L25
convert decimal to hex
python
def hex_to_int(value): """ Convert hex string like "\x0A\xE3" to 2787. """ if version_info.major >= 3: return int.from_bytes(value, "big") return int(value.encode("hex"), 16)
https://github.com/flyte/xbee-helper/blob/8b47675ad44d8a57defea459682d129379af348d/xbee_helper/device.py#L42-L48
convert decimal to hex
python
def char2hex(a: str): """Convert a hex character to its integer value. '0' becomes 0, '9' becomes 9 'A' becomes 10, 'F' becomes 15 'a' becomes 10, 'f' becomes 15 Returns -1 on error. """ if "0" <= a <= "9": return ord(a) - 48 elif "A" <= a <= "F": return ord(a) - 55 elif "a" <= a <= "f": # a-f return ord(a) - 87 return -1
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/lexer.py#L493-L509
convert decimal to hex
python
def hex_digit(coord, digit=1): """ Returns either the first or second digit of the hexadecimal representation of the given coordinate. :param coord: hexadecimal coordinate, int :param digit: 1 or 2, meaning either the first or second digit of the hexadecimal :return: int, either the first or second digit """ if digit not in [1,2]: raise ValueError('hex_digit can only get the first or second digit of a hex number, was passed digit={}'.format( digit )) return int(hex(coord)[1+digit], 16)
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L439-L450
convert decimal to hex
python
def convert_to_decimal(string): """ Decode the exif-gps format into a decimal point. '[51, 4, 1234/34]' -> 51.074948366 """ number_or_fraction = '(?:\d{1,2}) | (?:\d{1,10} \\ \d{1,10})' m = re.compile('''\[?\s? # opening bracket \d{{1,2}}\s?,\s? # first number {0} \s?,\s? # second number (can be a fraction) {0} \s?,\s? # third number (can be a fraction) \]?\s? # closing bracket '''.format(number_or_fraction), re.VERBOSE) if not m.match(string): raise ValueError h, m, s = re.sub('\[|\]', '', string).split(', ') result = int(h) if '/' in m: m = m.split('/') result += int(m[0]) * 1.0 / int(m[1]) / 60 else: result += int(m) * 1.0 / 60 if '/' in s: s = s.split('/') result += int(s[0]) * 1.0 / int(s[1]) / 3600 else: result += int(s) * 1.0 / 60 return result
https://github.com/FreekKalter/geoselect/blob/2c6ab869d50215eba21dce3e1770bcf8ecdb41f3/geoselect.py#L63-L90
convert decimal to hex
python
def dec_sexegesimal_to_decimal( self, dec): """ *Convert a declination from sexegesimal format to decimal degrees.* Precision should be respected. If a float is passed to this method, the same float will be returned (useful if unclear which format coordinates are in). The code will attempt to read the sexegesimal value in whatever form it is passed. Any of the following should be handled correctly: - ``+1:58:05.45341`` - ``01:5:05`` - ``+1 58 05.45341`` - ``-23h53m05s`` **Key Arguments:** - ``dec`` - DEC in sexegesimal format. **Return:** - ``decDeg`` -- declination converted to decimal degrees **Usage:** .. todo:: - replace dryxPython declination_sexegesimal_to_decimal with this version in all my code - replace coords_sex_to_dec in all code .. code-block:: python from astrocalc.coords import unit_conversion converter = unit_conversion( log=log ) dec = converter.dec_sexegesimal_to_decimal( dec="-23:45:21.23232" ) print dec # OUTPUT: -23.7558978667 """ self.log.info( 'starting the ``dec_sexegesimal_to_decimal`` method') import re # TEST TO SEE IF DECIMAL DEGREES PASSED try: dec = float(dec) if dec > -90. and dec < 90.: self.log.info( 'declination seems to already be in decimal degrees, returning original value' % locals()) return float(dec) except: pass # REMOVE SURROUNDING WHITESPACE dec = str(dec).strip() # LOOK FOR A MINUS SIGN. NOTE THAT -00 IS THE SAME AS 00. regex = re.compile( '^([\+\-]?(\d|[0-8]\d))\D+([0-5]\d)\D+([0-6]?\d(\.\d+)?)$') decMatch = regex.match(dec) if decMatch: degrees = decMatch.group(1) minutes = decMatch.group(3) seconds = decMatch.group(4) if degrees[0] == '-': sgn = -1 else: sgn = 1 degrees = abs(float(degrees)) minutes = float(minutes) seconds = float(seconds) # PRECISION TEST # 1s = .000277778 DEGREE # THEREFORE REPORT SECONDS TO A PRECISION = INPUT PRECISION + 4 decimalLen = len(repr(seconds).split(".")[-1]) precision = decimalLen + 4 decDeg = (degrees + (minutes / 60.0) + (seconds / 3600.0)) * sgn decDeg = "%0.*f" % (precision, decDeg) else: raise IOError( "could not convert dec to decimal degrees, could not parse sexegesimal input. Original value was `%(dec)s`" % locals()) decDeg = float(decDeg) self.log.debug('decDeg: %(decDeg)s' % locals()) self.log.info( 'completed the ``dec_sexegesimal_to_decimal`` method') return float(decDeg)
https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L90-L188
convert decimal to hex
python
def hexify(number): """ Convert integer to hex string representation, e.g. 12 to '0C' """ if( isinstance(number, int) == False ): raise TypeError('hexify(): expected integer, not {}'.format(type(number))) if number < 0: raise ValueError('Invalid number to hexify - must be positive') result = hex(int(number)).replace('0x', '').upper() if divmod(len(result), 2)[1] == 1: # Padding result = '0{}'.format(result) return result
https://github.com/timgabets/pynblock/blob/dbdb6d06bd7741e1138bed09d874b47b23d8d200/pynblock/tools.py#L44-L58
convert decimal to hex
python
def hexadecimal(token): """ Convert a strip of hexadecimal numbers into binary data. @type token: str @param token: String to parse. @rtype: str @return: Parsed string value. """ token = ''.join([ c for c in token if c.isalnum() ]) if len(token) % 2 != 0: raise ValueError("Missing characters in hex data") data = '' for i in compat.xrange(0, len(token), 2): x = token[i:i+2] d = int(x, 16) s = struct.pack('<B', d) data += s return data
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L121-L140
convert decimal to hex
python
def format_decimal(decimal): """ Formats a decimal number :param decimal: the decimal value :return: the formatted string value """ # strip trailing fractional zeros normalized = decimal.normalize() sign, digits, exponent = normalized.as_tuple() if exponent >= 1: normalized = normalized.quantize(1) return str(normalized)
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L200-L212
convert decimal to hex
python
def enhex(d, separator=''): """ Convert bytes to their hexadecimal representation, optionally joined by a given separator. Args: d(bytes): The data to convert to hexadecimal representation. separator(str): The separator to insert between hexadecimal tuples. Returns: str: The hexadecimal representation of ``d``. Examples: >>> from pwny import * >>> enhex(b'pwnypack') '70776e797061636b' >>> enhex(b'pwnypack', separator=' ') '70 77 6e 79 70 61 63 6b' """ v = binascii.hexlify(d).decode('ascii') if separator: return separator.join( v[i:i+2] for i in range(0, len(v), 2) ) else: return v
https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/codec.py#L234-L261
convert decimal to hex
python
def decimal_format(value, TWOPLACES=Decimal(100) ** -2): 'Format a decimal.Decimal like to 2 decimal places.' if not isinstance(value, Decimal): value = Decimal(str(value)) return value.quantize(TWOPLACES)
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/templatetags/customtags.py#L77-L81
convert decimal to hex
python
def int_to_padded_hex_byte(integer): """ Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C") """ to_hex = hex(integer) xpos = to_hex.find('x') hex_byte = to_hex[xpos+1 : len(to_hex)].upper() if len(hex_byte) == 1: hex_byte = ''.join(['0', hex_byte]) return hex_byte
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L36-L49
convert decimal to hex
python
def unhex(s): """Get the integer value of a hexadecimal number.""" bits = 0 for c in s: if '0' <= c <= '9': i = ord('0') elif 'a' <= c <= 'f': i = ord('a')-10 elif 'A' <= c <= 'F': i = ord('A')-10 else: break bits = bits*16 + (ord(c) - i) return bits
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/quopri.py#L175-L188
convert decimal to hex
python
def to_decimal(number, points=None): """ convert datatypes into Decimals """ if not is_number(number): return number number = float(decimal.Decimal(number * 1.)) # can't Decimal an int if is_number(points): return round(number, points) return number
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L103-L111
convert decimal to hex
python
def _dot_to_dec(ip, check=True): """Dotted decimal notation to decimal conversion.""" if check and not is_dot(ip): raise ValueError('_dot_to_dec: invalid IP: "%s"' % ip) octets = str(ip).split('.') dec = 0 dec |= int(octets[0]) << 24 dec |= int(octets[1]) << 16 dec |= int(octets[2]) << 8 dec |= int(octets[3]) return dec
https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L229-L239
convert decimal to hex
python
def dec_decimal_to_sexegesimal( self, dec, delimiter=":"): """ *Convert a declination between decimal degrees and sexegesimal.* Precision should be respected. **Key Arguments:** - ``dec`` -- DEC in decimal degrees. Will try and convert to float before performing calculation. - ``delimiter`` -- how to delimit the RA units. Default *:* **Return:** - ``sexegesimal`` -- ra in sexegesimal units **Usage:** .. todo:: - replace dec_to_sex in dryxPython in all code .. code-block:: python from astrocalc.coords import unit_conversion converter = unit_conversion( log=log ) dec = converter.dec_decimal_to_sexegesimal( dec="-3.454676456", delimiter=":" ) print dec # OUT: -03:27:16.8 """ self.log.info('starting the ``dec_decimal_to_sexegesimal`` method') import math # CONVERT DEC TO FLOAT try: self.log.debug("attempting to convert RA to float") dec = float(dec) except Exception, e: self.log.error( "could not convert RA to float - failed with this error: %s " % (str(e),)) return -1 # COMPLAIN IF DEC NOT BETWEEN -90 - 90 if dec > -90. and dec < 90.: pass else: self.log.error( "DEC must be between -90 - 90 degrees") return -1 if (dec >= 0): hemisphere = '+' else: hemisphere = '-' dec *= -1 # PRECISION TEST # 1s = .000277778 DEGREE # THEREFORE REPORT SECONDS TO A PRECISION = INPUT PRECISION - 4 decimalLen = len(repr(dec).split(".")[-1]) precision = decimalLen - 4 dec_deg = int(dec) dec_mm = int((dec - dec_deg) * 60) dec_ss = int(((dec - dec_deg) * 60 - dec_mm) * 60) dec_f = (((dec - dec_deg) * 60 - dec_mm) * 60) - dec_ss # SET PRECISION dec_f = repr(dec_f)[2:] dec_f = dec_f[:precision] if len(dec_f): dec_f = "." + dec_f if precision < 0: dec_f = "" sexegesimal = hemisphere + '%02d' % dec_deg + delimiter + \ '%02d' % dec_mm + delimiter + '%02d' % dec_ss + dec_f self.log.info('completed the ``dec_decimal_to_sexegesimal`` method') return sexegesimal
https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L363-L448
convert decimal to hex
python
def format_decimal(interval, value): """Return formatted decimal according to interval decimal place For example: interval = 0.33 (two decimal places) my_float = 1.1215454 Return 1.12 (return only two decimal places as string) If interval is an integer return integer part of my_number If my_number is an integer return as is """ interval = get_significant_decimal(interval) if isinstance(interval, Integral) or isinstance(value, Integral): return add_separators(int(value)) if interval != interval: # nan return str(value) if value != value: # nan return str(value) decimal_places = len(str(interval).split('.')[1]) my_number_int = str(value).split('.')[0] my_number_decimal = str(value).split('.')[1][:decimal_places] if len(set(my_number_decimal)) == 1 and my_number_decimal[-1] == '0': return my_number_int formatted_decimal = (add_separators(int(my_number_int)) + decimal_separator() + my_number_decimal) return formatted_decimal
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L327-L354
convert decimal to hex
python
def hex(self): """Return a hexadecimal representation of a BigFloat.""" sign = '-' if self._sign() else '' e = self._exponent() if isinstance(e, six.string_types): return sign + e m = self._significand() _, digits, _ = _mpfr_get_str2( 16, 0, m, ROUND_TIES_TO_EVEN, ) # only print the number of digits that are actually necessary n = 1 + (self.precision - 1) // 4 assert all(c == '0' for c in digits[n:]) result = '%s0x0.%sp%+d' % (sign, digits[:n], e) return result
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L537-L556
convert decimal to hex
python
def convert_Decimal(x, encoder): """ Called when an instance of U{decimal.Decimal<http:// docs.python.org/library/decimal.html#decimal-objects>} is about to be encoded to an AMF stream. @return: If the encoder is in 'strict' mode then C{x} will be converted to a float. Otherwise an L{pyamf.EncodeError} with a friendly message is raised. """ if encoder.strict is False: return float(x) raise pyamf.EncodeError('Unable to encode decimal.Decimal instances as ' 'there is no way to guarantee exact conversion. Use strict=False to ' 'convert to a float.')
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/adapters/_decimal.py#L15-L30
convert decimal to hex
python
def _dehex(s): """Liberally convert from hex string to binary string.""" import re import binascii # Remove all non-hexadecimal digits s = re.sub(br'[^a-fA-F\d]', b'', s) # binscii.unhexlify works in Python 2 and Python 3 (unlike # thing.decode('hex')). return binascii.unhexlify(s)
https://github.com/drj11/pypng/blob/b8220ca9f58e4c5bc1d507e713744fcb8c049225/code/pngsuite.py#L20-L29
convert decimal to hex
python
def hex_to_bytes(s): """ convert hex string to bytes """ if len(s) % 2: s = b'0' + s ia = [int(s[i:i+2], 16) for i in range(0, len(s), 2)] # int array return bs(ia) if PYTHON_MAJOR_VER == 3 else b''.join([chr(c) for c in ia])
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/utils.py#L43-L50
convert decimal to hex
python
def _decimal_to_128(value): """Converts a decimal.Decimal to BID (high bits, low bits). :Parameters: - `value`: An instance of decimal.Decimal """ with decimal.localcontext(_DEC128_CTX) as ctx: value = ctx.create_decimal(value) if value.is_infinite(): return _NINF if value.is_signed() else _PINF sign, digits, exponent = value.as_tuple() if value.is_nan(): if digits: raise ValueError("NaN with debug payload is not supported") if value.is_snan(): return _NSNAN if value.is_signed() else _PSNAN return _NNAN if value.is_signed() else _PNAN significand = int("".join([str(digit) for digit in digits])) bit_length = _bit_length(significand) high = 0 low = 0 for i in range(min(64, bit_length)): if significand & (1 << i): low |= 1 << i for i in range(64, bit_length): if significand & (1 << i): high |= 1 << (i - 64) biased_exponent = exponent + _EXPONENT_BIAS if high >> 49 == 1: high = high & 0x7fffffffffff high |= _EXPONENT_MASK high |= (biased_exponent & 0x3fff) << 47 else: high |= biased_exponent << 49 if sign: high |= _SIGN return high, low
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/decimal128.py#L107-L153
convert decimal to hex
python
def hex2dec(s): """ hex2dec 十六进制 to 十进制 :param s: :return: """ if not isinstance(s, str): s = str(s) return int(s.upper(), 16)
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L84-L93
convert decimal to hex
python
def decimal_to_digits(decimal, min_digits=None): """ Return the number of digits to the first nonzero decimal. Parameters ----------- decimal: float min_digits: int, minimum number of digits to return Returns ----------- digits: int, number of digits to the first nonzero decimal """ digits = abs(int(np.log10(decimal))) if min_digits is not None: digits = np.clip(digits, min_digits, 20) return digits
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/util.py#L751-L768
convert decimal to hex
python
def to_decimal(text): """ Takes a base91 char string and returns decimal """ if not isinstance(text, string_type): raise TypeError("expected str or unicode, %s given" % type(text)) if findall(r"[\x00-\x20\x7c-\xff]", text): raise ValueError("invalid character in sequence") text = text.lstrip('!') decimal = 0 length = len(text) - 1 for i, char in enumerate(text): decimal += (ord(char) - 33) * (91 ** (length - i)) return decimal if text != '' else 0
https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/base91.py#L34-L51
convert decimal to hex
python
def float_to_decimal(f): """ Convert a float to a 38-precision Decimal """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) return DECIMAL_CONTEXT.divide(numerator, denominator)
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L13-L17
convert decimal to hex
python
def decimal_to_hms(decimal_value): '''Converts from decimal degrees (for RA coords) to HH:MM:SS. Parameters ---------- decimal_value : float A decimal value to convert to hours, minutes, seconds. Negative values will be wrapped around 360.0. Returns ------- tuple A three element tuple is returned: (HH, MM, SS.ssss...) ''' # wrap to 360.0 if decimal_value < 0: dec_wrapped = 360.0 + decimal_value else: dec_wrapped = decimal_value # convert to decimal hours first dec_hours = dec_wrapped/15.0 if dec_hours < 0: negative = True dec_val = fabs(dec_hours) else: negative = False dec_val = dec_hours hours = trunc(dec_val) minutes_hrs = dec_val - hours minutes_mm = minutes_hrs * 60.0 minutes_out = trunc(minutes_mm) seconds = (minutes_mm - minutes_out)*60.0 if negative: hours = -hours return hours, minutes_out, seconds else: return hours, minutes_out, seconds
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L101-L146
convert decimal to hex
python
def to_decimal(self): """Returns an instance of :class:`decimal.Decimal` for this :class:`Decimal128`. """ high = self.__high low = self.__low sign = 1 if (high & _SIGN) else 0 if (high & _SNAN) == _SNAN: return decimal.Decimal((sign, (), 'N')) elif (high & _NAN) == _NAN: return decimal.Decimal((sign, (), 'n')) elif (high & _INF) == _INF: return decimal.Decimal((sign, (), 'F')) if (high & _EXPONENT_MASK) == _EXPONENT_MASK: exponent = ((high & 0x1fffe00000000000) >> 47) - _EXPONENT_BIAS return decimal.Decimal((sign, (0,), exponent)) else: exponent = ((high & 0x7fff800000000000) >> 49) - _EXPONENT_BIAS arr = bytearray(15) mask = 0x00000000000000ff for i in range(14, 6, -1): arr[i] = (low & mask) >> ((14 - i) << 3) mask = mask << 8 mask = 0x00000000000000ff for i in range(6, 0, -1): arr[i] = (high & mask) >> ((6 - i) << 3) mask = mask << 8 mask = 0x0001000000000000 arr[0] = (high & mask) >> 48 # Have to convert bytearray to bytes for python 2.6. # cdecimal only accepts a tuple for digits. digits = tuple( int(digit) for digit in str(_from_bytes(bytes(arr), 'big'))) with decimal.localcontext(_DEC128_CTX) as ctx: return ctx.create_decimal((sign, digits, exponent))
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/decimal128.py#L266-L307
convert decimal to hex
python
def ra_sexegesimal_to_decimal( self, ra ): """ *Convert a right-ascension from sexegesimal format to decimal degrees.* Precision should be respected. If a float is passed to this method, the same float will be returned (useful if unclear which format coordinates are in). The code will attempt to read the sexegesimal value in whatever form it is passed. Any of the following should be handled correctly - ``23:45:21.23232`` - ``23h45m21.23232s`` - ``23 45 21.23232`` - ``2 04 21.23232`` - ``04:45 21`` **Key Arguments:** - ``ra`` -- ra in sexegesimal units **Return:** - ``decimalDegrees`` **Usage:** .. code-block:: python - replace dryxPython ra_sexegesimal_to_decimal with this version in all my code from astrocalc.coords import unit_conversion converter = unit_conversion( log=log ) ra = converter.ra_sexegesimal_to_decimal( ra="04:45 21" ) print ra # OUTPUT: 71.3375 """ import re # TEST TO SEE IF DECIMAL DEGREES PASSED try: ra = float(ra) if ra >= 0. and ra <= 360.: self.log.info( 'RA seems to already be in decimal degrees, returning original value' % locals()) return float(ra) except: pass # REMOVE SURROUNDING WHITESPACE ra = str(ra).strip() regex = re.compile( '^(\+?(\d|[0-1]\d|2[0-3]))\D+([0-5]\d)\D+([0-6]?\d(\.\d*?)?)(s)?\s*?$') raMatch = regex.match(ra) if raMatch: degrees = raMatch.group(1) minutes = raMatch.group(3) seconds = raMatch.group(4) degrees = abs(float(degrees)) * 15.0 minutes = float(minutes) * 15.0 seconds = float(seconds) * 15.0 # PRECISION TEST # 1s ARCSEC = .000018519 DEGREE # THEREFORE REPORT SECONDS TO A PRECISION = INPUT PRECISION + 5 decimalLen = len(repr(seconds).split(".")[-1]) precision = decimalLen + 5 decimalDegrees = (degrees + (minutes / 60.0) + (seconds / 3600.0)) decimalDegrees = "%0.*f" % (precision, decimalDegrees) else: raise IOError( "could not convert ra to decimal degrees, could not parse sexegesimal input. Original value was `%(ra)s`" % locals()) raDeg = decimalDegrees self.log.debug('raDeg: %(decimalDegrees)s' % locals()) self.log.info( 'completed the ``ra_sexegesimal_to_decimal`` method') return float(raDeg)
https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L190-L278
convert decimal to hex
python
def hex2bin(hexstr): """Convert a hexdecimal string to binary string, with zero fillings. """ num_of_bits = len(hexstr) * 4 binstr = bin(int(hexstr, 16))[2:].zfill(int(num_of_bits)) return binstr
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/common.py#L4-L8
convert decimal to hex
python
def decimal128_to_decimal(b): "decimal128 bytes to Decimal" v = decimal128_to_sign_digits_exponent(b) if isinstance(v, Decimal): return v sign, digits, exponent = v return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/decfloat.py#L216-L222
convert decimal to hex
python
def format_decimal(self, altitude=None): """ Format decimal degrees with altitude """ coordinates = [str(self.latitude), str(self.longitude)] if altitude is None: altitude = bool(self.altitude) if altitude: if not isinstance(altitude, string_compare): altitude = 'km' coordinates.append(self.format_altitude(altitude)) return ", ".join(coordinates)
https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/point.py#L234-L247
convert decimal to hex
python
def set_decimal(self, pos, decimal): """Turn decimal point on or off at provided position. Position should be a value 0 to 3 with 0 being the left most digit on the display. Decimal should be True to turn on the decimal point and False to turn it off. """ if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Set bit 14 (decimal point) based on provided value. if decimal: self.buffer[pos*2+1] |= (1 << 6) else: self.buffer[pos*2+1] &= ~(1 << 6)
https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/AlphaNum4.py#L144-L156
convert decimal to hex
python
def validate_hex(value): """Validate that value has hex format.""" try: binascii.unhexlify(value) except Exception: raise vol.Invalid( '{} is not of hex format'.format(value)) return value
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/const_15.py#L261-L268
convert decimal to hex
python
def decimal_to_ratio(d): """Convert Decimal d to exact integer ratio (numerator, denominator). """ sign, digits, exp = d.as_tuple() if exp in ('F', 'n', 'N'): # INF, NAN, sNAN assert not d.is_finite() raise ValueError num = 0 for digit in digits: num = num * 10 + digit if sign: num = -num den = 10 ** -exp return (num, den)
https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L109-L122
convert decimal to hex
python
def to_decimal(number, strip='- '): ''' Converts a number to a string of decimals in base 10. >>> to_decimal(123) '123' >>> to_decimal('o123') '83' >>> to_decimal('b101010') '42' >>> to_decimal('0x2a') '42' ''' if isinstance(number, six.integer_types): return str(number) number = str(number) number = re.sub(r'[%s]' % re.escape(strip), '', number) # hexadecimal if number.startswith('0x'): return to_decimal(int(number[2:], 16)) # octal elif number.startswith('o'): return to_decimal(int(number[1:], 8)) # binary elif number.startswith('b'): return to_decimal(int(number[1:], 2)) else: return str(int(number))
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/util.py#L71-L103
convert decimal to hex
python
def formatDecimalMark(value, decimalmark='.'): """ Dummy method to replace decimal mark from an input string. Assumes that 'value' uses '.' as decimal mark and ',' as thousand mark. ::value:: is a string ::returns:: is a string with the decimal mark if needed """ # We have to consider the possibility of working with decimals such as # X.000 where those decimals are important because of the precission # and significant digits matters # Using 'float' the system delete the extre desimals with 0 as a value # Example: float(2.00) -> 2.0 # So we have to save the decimal length, this is one reason we are usnig # strings for results rawval = str(value) try: return decimalmark.join(rawval.split('.')) except: return rawval
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/__init__.py#L197-L216
convert decimal to hex
python
def signed_to_float(hex: str) -> float: """Convert signed hexadecimal to floating value.""" if int(hex, 16) & 0x8000: return -(int(hex, 16) & 0x7FFF) / 10 else: return int(hex, 16) / 10
https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L170-L175
convert decimal to hex
python
def rgb2hex(r: int, g: int, b: int) -> str: """ Convert rgb values to a hex code. """ return '{:02x}{:02x}{:02x}'.format(r, g, b)
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/trans.py#L416-L418
convert decimal to hex
python
def string_to_decimal(value, strict=True): """ Return a decimal corresponding to the string representation of a number. @param value: a string representation of an decimal number. @param strict: indicate whether the specified string MUST be of a valid decimal number representation. @return: the decimal value represented by the string. @raise ValueError: if the string doesn't represent a valid decimal, while the argument ``strict`` equals ``True``. """ if is_undefined(value): if strict: raise ValueError('The value cannot be null') return None try: return float(value) except ValueError: raise ValueError( 'The specified string "%s" does not represent an integer' % value)
https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/utils/cast.py#L187-L212
convert decimal to hex
python
def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
https://github.com/wanji/bitmap/blob/beb750530045e4f7cf665675bfb28f82d6325007/src/bitmap.py#L131-L137
convert decimal to hex
python
def _convert_coordinates_to_decimal_degrees( self): """ *convert coordinates to decimal degrees* """ self.log.info( 'starting the ``_convert_coordinates_to_decimal_degrees`` method') converter = unit_conversion( log=self.log ) # CONVERT ALL COORDINATES TO DECIMAL DEGREES if len(self.listOfCoordinates) and isinstance(self.listOfCoordinates[0], str): sources = [] sources[:] = [s.split(" ") for s in self.listOfCoordinates] else: sources = self.listOfCoordinates self.listOfCoordinates = [] # TEST IF CONVERSION IS REQUIRED try: ra = float(sources[0][0]) convert = False except: convert = True if convert == True: raDegs = [] raDegs[:] = [converter.ra_sexegesimal_to_decimal( ra=s[0]) for s in sources] decDegs = [] decDegs[:] = [converter.dec_sexegesimal_to_decimal( dec=s[1]) for s in sources] self.listOfCoordinates = [] self.listOfCoordinates[:] = [[raDeg, decDeg] for raDeg, decDeg in zip(raDegs, decDegs)] else: self.listOfCoordinates = [] self.listOfCoordinates[:] = [[float(s[0]), float(s[1])] for s in sources] self.log.info( 'completed the ``_convert_coordinates_to_decimal_degrees`` method') return None
https://github.com/thespacedoctor/neddy/blob/f32653b7d6a39a2c46c5845f83b3a29056311e5e/neddy/_basesearch.py#L40-L86
convert decimal to hex
python
def decimal(self, var, default=NOTSET, force=True): """Convenience method for casting to a decimal.Decimal Note: Casting """ return self._get(var, default=default, cast=Decimal, force=force)
https://github.com/miped/django-envy/blob/d7fe3c5dcad09e024c502e0f0e3a7c668ba15631/envy.py#L166-L172
convert decimal to hex
python
def set_decimal(self, pos, decimal): """Turn decimal point on or off at provided position. Position should be a value 0 to 3 with 0 being the left most digit on the display. Decimal should be True to turn on the decimal point and False to turn it off. """ if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Jump past the colon at position 2 by adding a conditional offset. offset = 0 if pos < 2 else 1 # Calculate the correct position depending on orientation if self.invert: pos = 4-(pos+offset) else: pos = pos+offset # Set bit 7 (decimal point) based on provided value. if decimal: self.buffer[pos*2] |= (1 << 7) else: self.buffer[pos*2] &= ~(1 << 7)
https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/SevenSegment.py#L102-L123
convert decimal to hex
python
def to_int(value: str) -> int: """ Robust to integer conversion, handling hex values, string representations, and special cases like `0x`. """ if is_0x_prefixed(value): if len(value) == 2: return 0 else: return int(value, 16) else: return int(value)
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L105-L116
convert decimal to hex
python
def hex(x): ''' x-->bytes | bytearray Returns-->bytes: hex-encoded ''' if isinstance(x, bytearray): x = bytes(x) return encode(x, 'hex')
https://github.com/sundarnagarajan/cffi_utils/blob/1d5ab2d2fcb962372228033106bc23f1d73d31fa/cffi_utils/py2to3.py#L191-L198
convert decimal to hex
python
def convert_decimal_to_hundreds(self, amount): """ Convert Decimal(10.10) to string "1010" :param amount: :return: """ return str((amount.quantize(Decimal('.01'), rounding=ROUND_FLOOR) * 100).quantize(Decimal('0')))
https://github.com/boris-savic/python-mbills/blob/a2147810c8c54b9242d9bcc2218622f1e19f9ac3/python_mbills/base.py#L87-L93
convert decimal to hex
python
def decimal_to_alpha(dec): """ expects: decimal between 0 and 100 returns: alpha value for rgba """ dec /= 100.0 alpha = hex(int(dec*65535))[2:] while len(alpha) < 4: alpha = '0' + alpha return alpha
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/utils.py#L81-L90
convert decimal to hex
python
def calc_hexversion(major=0, minor=0, micro=0, releaselevel='dev', serial=0): """Calculate the hexadecimal version number from the tuple version_info: :param major: integer :param minor: integer :param micro: integer :param relev: integer or string :param serial: integer :return: integerm always increasing with revision numbers """ try: releaselevel = int(releaselevel) except ValueError: releaselevel = RELEASE_LEVEL_VALUE.get(releaselevel, 0) hex_version = int(serial) hex_version |= releaselevel * 1 << 4 hex_version |= int(micro) * 1 << 8 hex_version |= int(minor) * 1 << 16 hex_version |= int(major) * 1 << 24 return hex_version
https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/version.py#L89-L109
convert decimal to hex
python
def int_to_decimal_str(integer): """ Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full stop decimal separator """ int_string = str(integer) if len(int_string) < 2: return "0." + int_string.zfill(2) else: return int_string[:-2] + "." + int_string[-2:]
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L64-L76
convert decimal to hex
python
def num2hexstring(number, size=1, little_endian=False): """ Converts a number to a big endian hexstring of a suitable size, optionally little endian :param {number} number :param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2. :param {boolean} little_endian - Encode the hex in little endian form :return {string} """ # if (type(number) != = 'number') throw new Error('num must be numeric') # if (num < 0) throw new RangeError('num is unsigned (>= 0)') # if (size % 1 !== 0) throw new Error('size must be a whole integer') # if (!Number.isSafeInteger(num)) throw new RangeError(`num (${num}) must be a safe integer`) size = size * 2 hexstring = hex(number)[2:] if len(hexstring) % size != 0: hexstring = ('0' * size + hexstring)[len(hexstring):] if little_endian: hexstring = reverse_hex(hexstring) return hexstring
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L29-L47
convert decimal to hex
python
def hex_timestamp_to_datetime(hex_timestamp): """Converts hex timestamp to a datetime object. >>> hex_timestamp_to_datetime('558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> hex_timestamp_to_datetime('0x558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> datetime.fromtimestamp(0x558BBCF9) datetime.datetime(2015, 6, 25, 8, 34, 1) """ if not hex_timestamp.startswith('0x'): hex_timestamp = '0x{0}'.format(hex_timestamp) return datetime.fromtimestamp(int(hex_timestamp, 16))
https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/date_parsers.py#L10-L23
convert decimal to hex
python
def to_hex( primitive: Primitives = None, hexstr: HexStr = None, text: str = None ) -> HexStr: """ Auto converts any supported value into its hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding """ if hexstr is not None: return HexStr(add_0x_prefix(hexstr.lower())) if text is not None: return HexStr(encode_hex(text.encode("utf-8"))) if is_boolean(primitive): return HexStr("0x1") if primitive else HexStr("0x0") if isinstance(primitive, (bytes, bytearray)): return HexStr(encode_hex(primitive)) elif is_string(primitive): raise TypeError( "Unsupported type: The primitive argument must be one of: bytes," "bytearray, int or bool and not str" ) if is_integer(primitive): return HexStr(hex(cast(int, primitive))) raise TypeError( "Unsupported type: '{0}'. Must be one of: bool, str, bytes, bytearray" "or int.".format(repr(type(primitive))) )
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L11-L42
convert decimal to hex
python
def to_hex_twos_compliment(value, bit_size): """ Converts integer value to twos compliment hex representation with given bit_size """ if value >= 0: return to_hex_with_size(value, bit_size) value = (1 << bit_size) + value hex_value = hex(value) hex_value = hex_value.rstrip("L") return hex_value
https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L82-L92
convert decimal to hex
python
def u64_to_hex16le(val): """! @brief Create 16-digit hexadecimal string from 64-bit register value""" return ''.join("%02x" % (x & 0xFF) for x in ( val, val >> 8, val >> 16, val >> 24, val >> 32, val >> 40, val >> 48, val >> 56, ))
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/utility/conversion.py#L92-L103
convert decimal to hex
python
def to_hex(x): """ Converts input to the hex string :param x: :return: """ if isinstance(x, bytearray): x = bytes(x) elif isinstance(x, (list, tuple)): x = bytes(bytearray(x)) if isinstance(x, basestring): return base64.b16encode(x).decode('ascii') else: raise ValueError('Unknown input argument type')
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L86-L99
convert decimal to hex
python
def hex_hash160(s, hex_format=False): """ s is in hex or binary format """ if hex_format and is_hex(s): s = unhexlify(s) return hexlify(bin_hash160(s))
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/hash.py#L37-L42
convert decimal to hex
python
def _bin_to_dec(ip, check=True): """Binary to decimal conversion.""" if check and not is_bin(ip): raise ValueError('_bin_to_dec: invalid IP: "%s"' % ip) if isinstance(ip, int): ip = str(ip) return int(str(ip), 2)
https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L279-L285
convert decimal to hex
python
def _convert_unsigned_long_to_lower_hex(self, value): """ Converts the provided unsigned long value to a hex string. :param value: the value to convert :type value: unsigned long :returns: value as a hex string """ result = bytearray(16) self._write_hex_long(result, 0, value) return result.decode("utf8")
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L258-L268
convert decimal to hex
python
def _hex_to_bytes(hex_id): """Encodes to hexadecimal ids to big-endian binary. :param hex_id: hexadecimal id to encode. :type hex_id: str :return: binary representation. :type: bytes """ if len(hex_id) <= 16: int_id = unsigned_hex_to_signed_int(hex_id) return struct.pack('>q', int_id) else: # There's no 16-bytes encoding in Python's struct. So we convert the # id as 2 64 bit ids and then concatenate the result. # NOTE: we count 16 chars from the right (:-16) rather than the left so # that ids with less than 32 chars will be correctly pre-padded with 0s. high_id = unsigned_hex_to_signed_int(hex_id[:-16]) high_bin = struct.pack('>q', high_id) low_id = unsigned_hex_to_signed_int(hex_id[-16:]) low_bin = struct.pack('>q', low_id) return high_bin + low_bin
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/protobuf/__init__.py#L89-L112
convert decimal to hex
python
def decimal_to_dms(decimal_value): '''Converts from decimal degrees (for declination coords) to DD:MM:SS. Parameters ---------- decimal_value : float A decimal value to convert to degrees, minutes, seconds sexagesimal format. Returns ------- tuple A four element tuple is returned: (sign, HH, MM, SS.ssss...) ''' if decimal_value < 0: negative = True dec_val = fabs(decimal_value) else: negative = False dec_val = decimal_value degrees = trunc(dec_val) minutes_deg = dec_val - degrees minutes_mm = minutes_deg * 60.0 minutes_out = trunc(minutes_mm) seconds = (minutes_mm - minutes_out)*60.0 if negative: degrees = degrees return '-', degrees, minutes_out, seconds else: return '+', degrees, minutes_out, seconds
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/coordutils.py#L61-L97
convert decimal to hex
python
def decimal_round(number, num_digits, rounding=ROUND_HALF_UP): """ Rounding for decimals with support for negative digits """ exp = Decimal(10) ** -num_digits if num_digits >= 0: return number.quantize(exp, rounding) else: return exp * (number / exp).to_integral_value(rounding)
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/utils.py#L22-L31
convert decimal to hex
python
def hex16_to_u64be(data): """! @brief Build 64-bit register value from big-endian 16-digit hexadecimal string""" return int(data[14:16] + data[12:14] + data[10:12] + data[8:10] + data[6:8] + data[4:6] + data[2:4] + data[0:2], 16)
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/utility/conversion.py#L109-L111
convert decimal to hex
python
def _convert_signed_hex(s): """Takes a signed hex string that begins with '0x' and converts it to a 16-character string representing an unsigned hex value. Examples: '0xd68adf75f4cfd13' => 'd68adf75f4cfd13' '-0x3ab5151d76fb85e1' => 'c54aeae289047a1f' """ if s.startswith('0x') or s.startswith('-0x'): s = '{0:x}'.format(struct.unpack('Q', struct.pack('q', int(s, 16)))[0]) return s.zfill(16)
https://github.com/Yelp/pyramid_zipkin/blob/ed8581b4466e9ce93d6cf3ecfbdde5369932a80b/pyramid_zipkin/request_helper.py#L37-L46
convert decimal to hex
python
def decimal(self, column, total=8, places=2): """ Create a new decimal column on the table. :param column: The column :type column: str :type total: int :type places: 2 :rtype: Fluent """ return self._add_column("decimal", column, total=total, places=places)
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/blueprint.py#L499-L512
convert decimal to hex
python
def to_hex_string(data): ''' Convert list of integers to a hex string, separated by ":" ''' if isinstance(data, int): return '%02X' % data return ':'.join([('%02X' % o) for o in data])
https://github.com/kipe/enocean/blob/99fa03f47004eef74c7987545c33ecd01af0de07/enocean/utils.py#L30-L34
convert decimal to hex
python
def normalize_hex(hex_value): """ Normalize a hexadecimal color value to the following form and return the result:: #[a-f0-9]{6} In other words, the following transformations are applied as needed: * If the value contains only three hexadecimal digits, it is expanded to six. * The value is normalized to lower-case. If the supplied value cannot be interpreted as a hexadecimal color value, ``ValueError`` is raised. Examples: >>> normalize_hex('#0099cc') '#0099cc' >>> normalize_hex('#0099CC') '#0099cc' >>> normalize_hex('#09c') '#0099cc' >>> normalize_hex('#09C') '#0099cc' >>> normalize_hex('0099cc') Traceback (most recent call last): ... ValueError: '0099cc' is not a valid hexadecimal color value. """ try: hex_digits = HEX_COLOR_RE.match(hex_value).groups()[0] except AttributeError: raise ValueError("'%s' is not a valid hexadecimal color value." % hex_value) if len(hex_digits) == 3: hex_digits = ''.join([2 * s for s in hex_digits]) return '#%s' % hex_digits.lower()
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/webcolors.py#L356-L396
convert decimal to hex
python
def _padded_hex(i, pad_width=4, uppercase=True): """ Helper function for taking an integer and returning a hex string. The string will be padded on the left with zeroes until the string is of the specified width. For example: _padded_hex(31, pad_width=4, uppercase=True) -> "001F" :param i: integer to convert to a hex string :param pad_width: (int specifying the minimum width of the output string. String will be padded on the left with '0' as needed. :param uppercase: Boolean indicating if we should use uppercase characters in the output string (default=True). :return: Hex string representation of the input integer. """ result = hex(i)[2:] # Remove the leading "0x" if uppercase: result = result.upper() return result.zfill(pad_width)
https://github.com/leonidessaguisagjr/unicodeutil/blob/c25c882cf9cb38c123df49fad365be67e5818928/unicodeutil/unicodeutil.py#L75-L91
convert decimal to hex
python
def decimal_day_to_day_hour_min_sec( self, daysFloat): """*Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- day as an integer - ``hoursInt`` -- hour as an integer (None if input precsion too low) - ``minsInt`` -- mins as an integer (None if input precsion too low) - ``secFloat`` -- secs as a float (None if input precsion too low) **Usage:** .. todo:: - replace `decimal_day_to_day_hour_min_sec` in all other code .. code-block:: python from astrocalc.times import conversions converter = conversions( log=log ) daysInt, hoursInt, minsInt, secFloat = converter.decimal_day_to_day_hour_min_sec( daysFloat=24.2453 ) print daysInt, hoursInt, minsInt, secFloat # OUTPUT: 24, 5, 53, None daysInt, hoursInt, minsInt, secFloat = converter.decimal_day_to_day_hour_min_sec( daysFloat=24.1232435454 ) print "%(daysInt)s days, %(hoursInt)s hours, %(minsInt)s mins, %(secFloat)s sec" % locals() # OUTPUT: 24 days, 2 hours, 57 mins, 28.242 sec """ self.log.info( 'starting the ``decimal_day_to_day_hour_min_sec`` method') daysInt = int(daysFloat) hoursFloat = (daysFloat - daysInt) * 24. hoursInt = int(hoursFloat) minsFloat = (hoursFloat - hoursInt) * 60. minsInt = int(minsFloat) secFloat = (minsFloat - minsInt) * 60. # DETERMINE PRECISION strday = repr(daysFloat) if "." not in strday: precisionUnit = "day" precision = 0 hoursInt = None minsInt = None secFloat = None else: lenDec = len(strday.split(".")[-1]) if lenDec < 2: precisionUnit = "day" precision = 0 hoursInt = None minsInt = None secFloat = None elif lenDec < 3: precisionUnit = "hour" precision = 0 minsInt = None secFloat = None elif lenDec < 5: precisionUnit = "minute" precision = 0 secFloat = None else: precisionUnit = "second" precision = lenDec - 5 if precision > 3: precision = 3 secFloat = "%02.*f" % (precision, secFloat) self.log.info( 'completed the ``decimal_day_to_day_hour_min_sec`` method') return daysInt, hoursInt, minsInt, secFloat
https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/times/conversions.py#L278-L363
convert decimal to hex
python
def decimal_str_to_int(decimal_string): """ Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @return integer The amount in cents """ int_string = decimal_string.replace('.', '') int_string = int_string.lstrip('0') return int(int_string)
https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L79-L89
convert decimal to hex
python
def print_hex(self, value, justify_right=True): """Print a numeric value in hexadecimal. Value should be from 0 to FFFF. """ if value < 0 or value > 0xFFFF: # Ignore out of range values. return self.print_str('{0:X}'.format(value), justify_right)
https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/AlphaNum4.py#L207-L213
convert decimal to hex
python
def decimal(anon, obj, field, val): """ Returns a random decimal """ return anon.faker.decimal(field=field)
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L67-L71
convert decimal to hex
python
def float_to_decimal(f): """ Convert a floating point number to a Decimal with no loss of information. Intended for Python 2.6 where casting float to Decimal does not work. """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) ctx = Context(prec=60) result = ctx.divide(numerator, denominator) while ctx.flags[Inexact]: ctx.flags[Inexact] = False ctx.prec *= 2 result = ctx.divide(numerator, denominator) return result
https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/utils.py#L27-L41
convert decimal to hex
python
def _convert_hexstr_base(hexstr, base): r""" Packs a long hexstr into a shorter length string with a larger base. Args: hexstr (str): string of hexidecimal symbols to convert base (list): symbols of the conversion base Example: >>> print(_convert_hexstr_base('ffffffff', _ALPHABET_26)) nxmrlxv >>> print(_convert_hexstr_base('0', _ALPHABET_26)) 0 >>> print(_convert_hexstr_base('-ffffffff', _ALPHABET_26)) -nxmrlxv >>> print(_convert_hexstr_base('aafffff1', _ALPHABET_16)) aafffff1 Sympy: >>> import sympy as sy >>> # Determine the length savings with lossless conversion >>> consts = dict(hexbase=16, hexlen=256, baselen=27) >>> symbols = sy.symbols('hexbase, hexlen, baselen, newlen') >>> haexbase, hexlen, baselen, newlen = symbols >>> eqn = sy.Eq(16 ** hexlen, baselen ** newlen) >>> newlen_ans = sy.solve(eqn, newlen)[0].subs(consts).evalf() >>> print('newlen_ans = %r' % (newlen_ans,)) >>> # for a 26 char base we can get 216 >>> print('Required length for lossless conversion len2 = %r' % (len2,)) >>> def info(base, len): ... bits = base ** len ... print('base = %r' % (base,)) ... print('len = %r' % (len,)) ... print('bits = %r' % (bits,)) >>> info(16, 256) >>> info(27, 16) >>> info(27, 64) >>> info(27, 216) """ if base is _ALPHABET_16: # already in hex, no conversion needed return hexstr baselen = len(base) x = int(hexstr, 16) # first convert to base 16 if x == 0: return '0' sign = 1 if x > 0 else -1 x *= sign digits = [] while x: digits.append(base[x % baselen]) x //= baselen if sign < 0: digits.append('-') digits.reverse() newbase_str = ''.join(digits) return newbase_str
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L639-L695
convert decimal to hex
python
def fix_coordinate_decimal(d): """ Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal. Round them down to 5 decimals :param dict d: Metadata :return dict d: Metadata """ try: for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]): d["geo"]["geometry"]["coordinates"][idx] = round(n, 5) except Exception as e: logger_misc.error("fix_coordinate_decimal: {}".format(e)) return d
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L143-L156
convert decimal to hex
python
def from_decimal(number, width=1): """ Takes a decimal and returns base91 char string. With optional parameter for fix with output """ text = [] if not isinstance(number, int_type): raise TypeError("Expected number to be int, got %s", type(number)) elif not isinstance(width, int_type): raise TypeError("Expected width to be int, got %s", type(number)) elif number < 0: raise ValueError("Expected number to be positive integer") elif number > 0: max_n = ceil(log(number) / log(91)) for n in _range(int(max_n), -1, -1): quotient, number = divmod(number, 91**n) text.append(chr(33 + quotient)) return "".join(text).lstrip('!').rjust(max(1, width), '!')
https://github.com/rossengeorgiev/aprs-python/blob/94b89a6da47a322129484efcaf1e82f6a9932891/aprslib/base91.py#L54-L74
convert decimal to hex
python
def decimal_to_dms(value, precision): ''' Convert decimal position to degrees, minutes, seconds in a fromat supported by EXIF ''' deg = math.floor(value) min = math.floor((value - deg) * 60) sec = math.floor((value - deg - min / 60) * 3600 * precision) return ((deg, 1), (min, 1), (sec, precision))
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/geo.py#L114-L122
convert decimal to hex
python
def from_ascii_hex(text: str) -> int: """Converts to an int value from both ASCII and regular hex. The format used appears to vary based on whether the command was to get an existing value (regular hex) or set a new value (ASCII hex mirrored back from original command). Regular hex: 0123456789abcdef ASCII hex: 0123456789:;<=>? """ value = 0 for index in range(0, len(text)): char_ord = ord(text[index:index + 1]) if char_ord in range(ord('0'), ord('?') + 1): digit = char_ord - ord('0') elif char_ord in range(ord('a'), ord('f') + 1): digit = 0xa + (char_ord - ord('a')) else: raise ValueError( "Response contains invalid character.") value = (value * 0x10) + digit return value
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L30-L49
convert decimal to hex
python
def print_hex(self, value, justify_right=True): """Print a numeric value in hexadecimal. Value should be from 0 to FFFF. """ if value < 0 or value > 0xFFFF: # Ignore out of range values. return self.print_number_str('{0:X}'.format(value), justify_right)
https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/SevenSegment.py#L198-L204
convert decimal to hex
python
def dec2str(n): """ decimal number to string. """ s = hex(int(n))[2:].rstrip('L') if len(s) % 2 != 0: s = '0' + s return hex2str(s)
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L163-L170
convert decimal to hex
python
def ra_decimal_to_sexegesimal( self, ra, delimiter=":"): """ *Convert a right-ascension between decimal degrees and sexegesimal.* Precision should be respected. **Key Arguments:** - ``ra`` -- RA in decimal degrees. Will try and convert to float before performing calculation. - ``delimiter`` -- how to delimit the RA units. Default *:* **Return:** - ``sexegesimal`` -- ra in sexegesimal units **Usage:** .. todo:: - replace ra_to_sex from dryxPython in all code .. code-block:: python from astrocalc.coords import unit_conversion converter = unit_conversion( log=log ) ra = converter.ra_decimal_to_sexegesimal( ra="-23.454676456", delimiter=":" ) print ra # OUT: 22:26:10.87 """ self.log.info('starting the ``ra_decimal_to_sexegesimal`` method') # CONVERT RA TO FLOAT try: self.log.debug("attempting to convert RA to float") ra = float(ra) except Exception, e: self.log.error( "could not convert RA to float - failed with this error: %s " % (str(e),)) return -1 # COMPLAIN IF RA NOT BETWEEN -360 - 360 if ra > 0. and ra < 360.: pass elif ra < 0 and ra > -360.: ra = 360. + ra else: self.log.error( "RA must be between 0 - 360 degrees") return -1 # PRECISION TEST # 1s ARCSEC = .000018519 DEGREE # THEREFORE REPORT SECONDS TO A PRECISION = INPUT PRECISION - 5 decimalLen = len(repr(ra).split(".")[-1]) precision = decimalLen - 5 # CALCULATION FROM DECIMAL DEGREES import math ra_hh = int(ra / 15) ra_mm = int((ra / 15 - ra_hh) * 60) ra_ss = int(((ra / 15 - ra_hh) * 60 - ra_mm) * 60) ra_ff = ((ra / 15 - ra_hh) * 60 - ra_mm) * 60 - ra_ss # SET PRECISION ra_ff = repr(ra_ff)[2:] ra_ff = ra_ff[:precision] if len(ra_ff): ra_ff = "." + ra_ff if precision < 0: ra_ff = "" sexegesimal = '%02d' % ra_hh + delimiter + '%02d' % ra_mm + \ delimiter + '%02d' % ra_ss + ra_ff self.log.info('completed the ``ra_decimal_to_sexegesimal`` method') return sexegesimal
https://github.com/thespacedoctor/astrocalc/blob/dfbebf9b86d7b2d2110c48a6a4f4194bf8885b86/astrocalc/coords/unit_conversion.py#L280-L361
convert decimal to hex
python
def to_int(value=None, hexstr=None, text=None): """ Converts value to it's integer representation. Values are converted this way: * value: * bytes: big-endian integer * bool: True => 1, False => 0 * hexstr: interpret hex as integer * text: interpret as string of digits, like '12' => 12 """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return int(hexstr, 16) elif text is not None: return int(text) elif isinstance(value, bytes): return big_endian_to_int(value) elif isinstance(value, str): raise TypeError("Pass in strings with keyword hexstr or text") else: return int(value)
https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L118-L141
convert decimal to hex
python
def decimal(self, prompt, default=None, lower=None, upper=None): """Prompts user to input decimal, with optional default and bounds.""" prompt = prompt if prompt is not None else "Enter a decimal number" prompt += " [{0}]: ".format(default) if default is not None else ': ' return self.input( curry(filter_decimal, default=default, lower=lower, upper=upper), prompt )
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L189-L196
convert decimal to hex
python
def _parse_canonical_decimal128(doc): """Decode a JSON decimal128 to bson.decimal128.Decimal128.""" d_str = doc['$numberDecimal'] if len(doc) != 1: raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,)) if not isinstance(d_str, string_type): raise TypeError('$numberDecimal must be string: %s' % (doc,)) return Decimal128(d_str)
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/json_util.py#L713-L720
convert decimal to hex
python
def rgb_to_hex(rgba): """ expects: rgba value, ex: 0000/0000/0000/dddd returns: hex value, ex: #000000 ignores alpha value """ rgba = rgba.split('/') hex_value = '#' + rgba[0][:2] + rgba[1][:2] + rgba[2][:2] return hex_value
https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/utils.py#L55-L63
convert decimal to hex
python
def dec2dec(dec): """ Convert sexegessimal RA string into a float in degrees. Parameters ---------- dec : string A string separated representing the Dec. Expected format is `[+- ]hh:mm[:ss.s]` Colons can be replaced with any whit space character. Returns ------- dec : float The Dec in degrees. """ d = dec.replace(':', ' ').split() if len(d) == 2: d.append(0.0) if d[0].startswith('-') or float(d[0]) < 0: return float(d[0]) - float(d[1]) / 60.0 - float(d[2]) / 3600.0 return float(d[0]) + float(d[1]) / 60.0 + float(d[2]) / 3600.0
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/angle_tools.py#L38-L59
convert decimal to hex
python
def hex_to_rgb(hex_value): """ Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an ``rgb()`` triplet specifying that color. The hexadecimal value will be normalized before being converted. Examples: >>> hex_to_rgb('#fff') (255, 255, 255) >>> hex_to_rgb('#000080') (0, 0, 128) """ hex_digits = normalize_hex(hex_value) return tuple([int(s, 16) for s in (hex_digits[1:3], hex_digits[3:5], hex_digits[5:7])])
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/webcolors.py#L650-L666
convert decimal to hex
python
def _parse_raw_bytes(raw_bytes): """Convert a string of hexadecimal values to decimal values parameters Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to: 46, 241, [128, 40, 0, 26, 1, 0] :param raw_bytes: string of hexadecimal values :returns: 3 decimal values """ bytes_list = [int(x, base=16) for x in raw_bytes.split()] return bytes_list[0], bytes_list[1], bytes_list[2:]
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L47-L57
convert decimal to hex
python
def hex2term(hexval: str, allow_short: bool = False) -> str: """ Convert a hex value into the nearest terminal code number. """ return rgb2term(*hex2rgb(hexval, allow_short=allow_short))
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/trans.py#L380-L382
convert decimal to hex
python
def hex2termhex(hexval: str, allow_short: bool = False) -> str: """ Convert a hex value into the nearest terminal color matched hex. """ return rgb2termhex(*hex2rgb(hexval, allow_short=allow_short))
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/trans.py#L385-L387