From e06fe1c8f845e6e55ff61c1628c586f49c9d09dc Mon Sep 17 00:00:00 2001 From: femike Date: Tue, 27 Nov 2018 09:27:13 +0500 Subject: [PATCH] Add convert from 8bit binary to hex --- README.md | 5 +++++ lib/hexbin-view.js | 21 ++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 608ba8c..8765218 100644 --- a/README.md +++ b/README.md @@ -8,3 +8,8 @@ Highlight a number in the editor, then use the ket shortcut or choose from the menu to toggle the conversion. ![screenshot](https://github.com/zaidt/hexbin/blob/master/resources/hexbin.png?raw=true) + +For convert 8bit binary to hex write it in format: +``` +0b00000001 +``` diff --git a/lib/hexbin-view.js b/lib/hexbin-view.js index 5ba63f6..7059b6f 100644 --- a/lib/hexbin-view.js +++ b/lib/hexbin-view.js @@ -36,7 +36,12 @@ export default class HexbinView { hex = '0x' + this.dec2hex(dec); } this.element.textContent = "Hex:" + hex + " Bin:" + this.formatBinary(bin) + " Dec:" + dec; - } else { + } else if (selection.length == 10 && selection.toUpperCase().substr(-10, 2) == '0B') { + bin = selection.substr(2, 10); + hex = this.bin2hex(bin); + dec = this.bin2dec(bin); + this.element.textContent = "Hex:" + hex + " Bin:" + this.formatBinary(bin) + " Dec:" + dec; + } else { this.element.textContent = "Invalid"; } } @@ -49,6 +54,20 @@ export default class HexbinView { return (+dec).toString(16); } + bin2dec(bin){ + return parseInt(bin, 2).toString(10); + } + + bin2hex(bin) { + hex = parseInt(bin, 2).toString(16); + + if(hex.toString().length > 1) { + return "0x" + hex.toString().toUpperCase(); + } + + return "0x0" + hex.toString().toUpperCase(); + } + formatBinary(bin) { str = ""; remainder = bin.length % 8;