Skip to content

Instantly share code, notes, and snippets.

@pwxcoo
Last active September 21, 2018 09:57
Show Gist options
  • Save pwxcoo/320509b94f5ed53b77b03c02ec7c54c7 to your computer and use it in GitHub Desktop.
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
#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;
}
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")
@pwxcoo
Copy link
Author

pwxcoo commented Sep 21, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment