Last active
September 21, 2018 09:57
-
-
Save pwxcoo/320509b94f5ed53b77b03c02ec7c54c7 to your computer and use it in GitHub Desktop.
1. print double type value to binary/hexadecimal expression in c++ 2. double parser for converting binary to double in Python
This file contains hidden or 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
#include <cstdio> | |
#include <cstring> | |
#include <algorithm> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <stack> | |
#include <bitset> | |
#include <cstdlib> | |
#include <cmath> | |
#include <set> | |
#include <list> | |
#include <deque> | |
#include <map> | |
#include <queue> | |
#include <unordered_map> | |
#include <unordered_set> | |
#include <assert.h> | |
using namespace std; | |
typedef long long ll; | |
const int INF = 0x7fffffff; | |
const double eps = 1e-8; | |
int main() | |
{ | |
double num = 1.00; | |
unsigned long long v = num; | |
memcpy(&v, &num, sizeof(num)); | |
cout << hex << v << endl; | |
return 0; | |
} |
This file contains hidden or 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_parser(d): | |
sign = 1 if d[0] == '0' else -1 | |
e = 2 ** (int(d[1:12], 2) - 1023) | |
f = 1 + sum([2 ** -(i+1) if d[12 + i] == '1' else 0 for i in range(52)]) | |
if d[1:12] == "1" * 11: | |
if f == 1: | |
return "INF" if sign == 1 else "-INF" | |
else: | |
return "NaN" | |
return sign * e * f | |
def float_to_bin(value): # For testing. | |
""" Convert float to 64-bit binary string. """ | |
[d] = struct.unpack(">Q", struct.pack(">d", value)) | |
return '{:064b}'.format(d) | |
import random | |
for i in range(50): | |
r = random.uniform(-1e10, 1e10) | |
assert double_parser(float_to_bin(r)) == r, f'test {r} failed' | |
assert double_parser("0 11111111111 0000000000000000000000000000000000000000000000000000".replace(" ", "")) == "INF" | |
assert double_parser("1 11111111111 0000000000000000000000000000000000000000000000000000".replace(" ", "")) == "-INF" | |
assert double_parser("0 11111111111 0000000000000000000000000000000000000000000000000001".replace(" ", "")) == "NaN" | |
assert double_parser("0 11111111111 1000000000000000000000000000000000000000000000000001".replace(" ", "")) == "NaN" | |
assert double_parser("0 11111111111 1111111111111111111111111111111111111111111111111111".replace(" ", "")) == "NaN" | |
print("Accpet") |
Author
pwxcoo
commented
Sep 21, 2018
- float - wiki
- double - wiki
- Double(IEEE754) Online Parser
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment