【python】bin/dec/hex/bnr进制转换函数及fp32转十六进制

简介: 【python】bin/dec/hex/bnr进制转换函数及fp32转十六进制

 

我们的目标是┏ (゜ω゜)=☞芯片前端全栈工程师~喵!

前言

不知道为什么,给脚本专栏选的这个logo有种怪怪的感觉(⊙o⊙)…

为方便后续一些脚本工作,将常用的进制转换函数汇总。所有函数均为字符串输入输出,且不加0x、0b等关键字,以便后续灵活调用。基于这些字符串输入输出的函数,可以非常灵活的根据需求拼接更加复杂的行为:

TO->>> 十进制 二进制源码 二进制补码 十六进制
十进制   dec_to_bin dec_to_bnr dec_to_hex
二进制源码 bin_to_dec   bin_to_bnr bin_to_hex
二进制补码 bnr_to_dec bnr_to_bin   bnr_to_hex
十六进制 hex_to_dec hex_to_bin hex_to_bnr  
FP32       float_to_hex

函数

dec_to_bin

十进制转二进制源码:

1. def dec_to_bin(i: str) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  return format(int(i),'b')#08b

测试:

1. print(dec_to_bin("10"))
2. print(dec_to_bin("-10"))
3. 
4. 1010
5. -1010

dec_to_bnr

十进制转二进制补码,我参考了网上的代码,稍作修改:

1. def dec_to_bnr(i: int, lenth: int = 1) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  dec = int(i)
5.  digits = (len(bin(dec)) - 3 + 1) if dec < 0 else (len(bin(dec)) - 2)
6.  if digits >= lenth:
7.    lenth = digits
8.  pattern = f"{dec & int('0b' + '1' * lenth, 2):0{lenth}b}"
9.  return "".join(code for code in pattern)

测试:

1. print(dec_to_bnr("10"))
2. print(dec_to_bnr("-10"))
3. 
4. 1010
5. 10110

dec_to_hex

十进制转十六进制:

1. def dec_to_hex(i: str) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  if i.startswith("-"):
5.    i = re.sub("-", "", i)
6.    return "-" + str(hex(int(i)))[2:]
7.  else:
8.    return str(hex(int(i)))[2:]

测试:

1. print(dec_to_hex("10"))
2. print(dec_to_hex("-10"))
3. 
4. a
5. -a

bin_to_dec

二进制转十进制:

1. def bin_to_dec(i: str) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  return str(int(str(i), 2))

测试:

1. print(bin_to_dec("0101"))
2. print(bin_to_dec("-0101"))
3. 
4. 5
5. -5

bin_to_bnr

二进制源码转二进制补码:

1. def bin_to_bnr(i: str) -> str:
2.  return dec_to_bnr(bin_to_dec(i))

测试:

1. print(bin_to_bnr("1010"))
2. print(bin_to_bnr("-1010"))
3. 
4. 1010
5. 10110

bin_to_hex

二进制原码转十六进制:

1. def bin_to_hex(i: str) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  if i.startswith("-"):
5.    i = re.sub("-", "", i)
6.    return "-" + str(hex(int(i, 2)))[2:]
7.  else:
8.    return str(hex(int(i, 2)))[2:]

测试:

1. print(bin_to_hex("1010"))
2. print(bin_to_hex("-1010"))
3. 
4. a
5. -a

bnr_to_dec

二进制补码转十进制,也是在参考了网上的代码:

1. def bnr_to_dec(i: str) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  for num in i:
5.    if num not in ["0", "1"]:
6.      raise ValueError("Not bin str")
7.  if i.startswith("0"):
8.    dec = int(i, 2)
9.  else:
10.     dec = int(i[1:], 2) - 0x01
11.     dec = -(~dec & int("0b" + "1" * (len(i) - 1), 2))
12.   return str(dec)

测试:

1. print(bnr_to_dec("010011"))
2. print(bnr_to_dec("1010011"))
3. 
4. 19
5. -45

bnr_to_bin

二进制补码转二进制原码:

1. def bnr_to_bin(i: str) -> str:
2.  return dec_to_bin(bnr_to_dec(i))

bnr_to_hex

二进制补码转十六进制,这个场景必然是要把补码还原为原本的数,再显示十六进制,否则直接用bin_to_hex就够了:

1. def bnr_to_hex(i: str) -> str:
2.  return dec_to_hex(bnr_to_dec(i))

测试:

1. print(bnr_to_hex("10100"))
2. print(bnr_to_hex("01001"))
3. 
4. -c
5. 9

hex_to_dec

十六进制转十进制:

1. def hex_to_dec(i: str) -> str:
2.  if not isinstance(i, str):
3.    raise TypeError("Not str input")
4.  return str(int(i, 16))

测试:

1. print(hex_to_dec("a"))
2. print(hex_to_dec("-a"))
3. 
4. 10
5. -10

hex_to_bin

十六进制转二进制:

1. def hex_to_bin(i: str) -> str:
2.  return dec_to_bin(hex_to_dec(i))

hex_to_bnr

十六进制转补码:

1. def hex_to_bnr(i: str) -> str:
2.  return dec_to_bnr(hex_to_dec(i))

float_to_hex

fp32(float)类型转十六进制,这个也是从网上学来的(感恩家人!):

1. import struct
2. def float_to_hex(i: str) -> str:
3.  f = float(i)
4.  h = hex(struct.unpack('<I', struct.pack('<f', f))[0])
5.  return str(h)[2:]

测试:

1. print(float_to_hex("17.5"))
2. print(float_to_hex("-17.5"))
3. 
4. 418c0000
5. c18c0000


相关文章
|
4天前
|
存储 缓存 算法
Python中的hash函数
Python中的hash函数
|
6天前
|
Python
Python学习笔记---函数
这篇文章是一份Python函数学习的笔记,涵盖了使用函数的优势、内置函数的调用、自定义函数的定义、函数参数的不同类型(必须参数、关键字参数、默认参数、可变参数)、有返回值和无返回值的函数、形参和实参、变量作用域、返回函数、递归函数、匿名函数、偏函数以及输入和输出函数等多个函数相关的主题。
|
13天前
|
Python
【Leetcode刷题Python】剑指 Offer 30. 包含min函数的栈
本文提供了实现一个包含min函数的栈的Python代码,确保min、push和pop操作的时间复杂度为O(1)。
13 4
|
5天前
|
Python
Python 函数
Python 函数
7 0
|
8天前
|
程序员 Shell 开发工具
[oeasy]python029_ until_直接跳转到_unt_breakpoint_断点函数
回顾早期计算机操作员多为女性,她们甚至发明了“bug”这个词。为了体验调试过程,我们故意在Python脚本中引入了一个拼写错误,并通过直接运行程序遇到了`NameError`。 通过`until`命令,我们可以快速跳转到指定行执行,这对于大型项目非常有用。此外,`continue`(或简写`c`)命令则会一直执行到下一个断点或程序结束。我们还可以在代码中使用`breakpoint()`设置断点,配合`continue`命令使用,实现快速跳转至特定位置进行调试。 这些技巧使调试过程变得高效且有趣,如同解开谜题一般。下次我们将探讨如何在调试过程中动态设置与取消断点。
18 0
|
12天前
|
Python
Python使用函数检查阿姆斯特朗数
记住,要检查一个范围内所有的阿姆斯特朗数,你可以简单地遍历这个范围,并用这个函数来检查每一个数。这种方法虽然简单,但非常管用,特别是在解决需要识别特定数学属性数字的问题时。
10 0
|
13天前
|
Python
【python笔记】使用zip函数迭代多个可迭代对象
【python笔记】使用zip函数迭代多个可迭代对象
|
开发者 Python
|
开发者 Python
|
7天前
|
算法 程序员 开发工具
百万级Python讲师又一力作!Python编程轻松进阶,豆瓣评分8.1
在学习Python的旅程中你是否正在“绝望的沙漠”里徘徊? 学完基础教程的你,是否还在为选择什么学习资料犹豫不决,不知从何入手,提高自己?
百万级Python讲师又一力作!Python编程轻松进阶,豆瓣评分8.1