Created
October 10, 2021 16:07
-
-
Save nonodev96/eb327d96140fbd80a6cd5349ca55c839 to your computer and use it in GitHub Desktop.
ieee754 - 32 bits, 64 bits
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
| export function float32ToBin(float32: number): string { | |
| let str = ""; | |
| const c = new Uint8Array(new Float32Array([float32]).buffer, 0, 4); | |
| for (const element of Array.from(c).reverse()) { | |
| str += element.toString(2).padStart(8, '0'); | |
| } | |
| return str; | |
| } | |
| export function float64ToBin(float64: number): string { | |
| let str = ""; | |
| const c = new Uint8Array(new Float64Array([float64]).buffer, 0, 8); | |
| for (const element of Array.from(c).reverse()) { | |
| str += element.toString(2).padStart(8, '0'); | |
| } | |
| return str; | |
| } | |
| export function convertBinaryIEEE754_32bits_ToNumber(str: string): number { | |
| if (str.length !== 32) throw new Error("Binary cannot be converted because the length is not 32.") | |
| const arr = []; | |
| for (let i = 0; i < str.length; i += 8) { | |
| const inner = str.slice(i, i + 8); | |
| arr.push(parseInt(inner, 2)); | |
| } | |
| const c = new Uint8Array(arr); | |
| return new DataView(c.buffer, 0, 4).getFloat32(0); | |
| } | |
| export function convertBinaryIEEE754_64bits_ToNumber(str: string): number { | |
| if (str.length !== 64) throw new Error("Binary cannot be converted because the length is not 64.") | |
| const arr = []; | |
| for (let i = 0; i < str.length; i += 8) { | |
| const inner = str.slice(i, i + 8); | |
| arr.push(parseInt(inner, 2)); | |
| } | |
| const c = new Uint8Array(arr); | |
| return new DataView(c.buffer, 0, 8).getFloat64(0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment