Last active
September 5, 2019 08:51
-
-
Save taketakeyyy/3009b1ddabce91aa7a6950f34720fe77 to your computer and use it in GitHub Desktop.
数値を2進数の文字列(64bit長)に変換する。2進数の文字列を数値に変換する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
def double_to_hex(f): | |
""" float値を16進数文字列に変換する | |
参考: https://note.nkmk.me/python-float-hex/ | |
""" | |
return hex(struct.unpack('>Q', struct.pack('>d', f))[0]) | |
def double_to_bin(f): | |
""" 数値を2進数の文字列(64bit長)に変換する | |
double_to_bin(1.0) => 0b0011111111110000000000000000000000000000000000000000000000000000 | |
double_to_bin(-1.0) => 0b1011111111110000000000000000000000000000000000000000000000000000 | |
""" | |
b = bin(int(double_to_hex(f), 16)) | |
bits = b[2:] | |
if len(bits) < 64: # 0が省略されてるとき | |
b = b[0:2] + "0"*(64-len(bits)) + bits | |
return b | |
def bin_to_double(b): | |
""" 2進数の文字列をfloat(64bitの倍精度浮動小数点数)に変換する | |
bin_to_double("0b0011111111110000000000000000000000000000000000000000000000000000") => 1.0 | |
bin_to_double("0b1011111111110000000000000000000000000000000000000000000000000000") => -1.0 | |
参考: https://codeday.me/jp/qa/20190324/435461.html | |
""" | |
q = int(b, 0) | |
b8 = struct.pack("Q", q) | |
return struct.unpack("d", b8)[0] | |
b = double_to_bin(33.) | |
print(b) | |
# 0b0100000001000000100000000000000000000000000000000000000000000000 | |
d = bin_to_double(b) | |
print(d) | |
# 33.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment