negative number representation in binary code example
Example 1: decimal to binary
import java.util.*;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dec = sc.nextInt();
StringBuffer sb = new StringBuffer();
while(dec!=0)
{
sb.append(dec%2);
dec=dec/2;
}
System.out.println(sb.reverse());
}
}
Example 2: converting float to binary 16
import struct
#################### bin32 ################################
# import bitstring
# f1 = bitstring.BitArray(float=0.456789, length=32)
# # f1 = bitstring.BitArray(float=0.456789, length=16)
# print(f1.bin)
# print("0011011101001111")
#################### bin32 ################################
def convertFloatToBin16(x):
k = struct.pack('>e', x)
z = ''.join(format(i, '08b') for i in k)
return str(z)
print(convertFloatToBin16(0.9945678))