Skip to content
This repository has been archived by the owner on Oct 15, 2022. It is now read-only.

Commit

Permalink
Text Converter: Fix binary conversion bug. (#4526)
Browse files Browse the repository at this point in the history
* Fix binary-to-decimal and binary-to-hexadecimal conversion bug.

* Lazy #4566 fix.
  • Loading branch information
vonaka authored and moollaza committed Jan 30, 2018
1 parent c04f35c commit 928eb99
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions share/goodie/text_converter/text_converter.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ DDH.text_converter = DDH.text_converter || {};
$convert_selects,
$convert_from_select,
$convert_to_select,
$convert_from_textarea,
$convert_from_textarea,
$convert_to_textarea;

// TextConverter: A singleton object that performs all the text conversions
Expand All @@ -29,7 +29,10 @@ DDH.text_converter = DDH.text_converter || {};
var to_type = $convert_to_select.val();
var from = $convert_from_textarea.val();

if(from_type === "binary" && to_type === "hexadecimal") {
if(from_type === "decimal" && to_type === "binary") {
return parseInt(from, 10).toString(2);

} else if(from_type === "binary" && to_type === "hexadecimal") {
return TextConverter.binaryToHex(from);

} else if(from_type === "binary" && to_type === "base64") {
Expand Down Expand Up @@ -129,14 +132,8 @@ DDH.text_converter = DDH.text_converter || {};
},

binaryToDecimal: function(binary) {
var octet = binary.replace(/\s/g, "").match(/.{1,8}/g);
var dec_cache = [];

for(var i = 0; i < octet.length; i++) {
dec_cache.push(parseInt(octet[i], 2));
}

return dec_cache.join(" ");
binary = binary.replace(/\s+/g, "");
return parseInt(binary, 2);
},

binaryToText: function(text) {
Expand All @@ -146,19 +143,28 @@ DDH.text_converter = DDH.text_converter || {};
},

binaryToHex: function(binaryString) {
var binaryString = binaryString.replace(/\s/g, "");
var binaryString = binaryString.replace(/\s+/g, "");
var output = "";

// For every 4 bits in the binary string
for(var i = 0; i < binaryString.length; i += 4) {
for(var i = -4; i >= -binaryString.length; i -= 4) {
var bytes = binaryString.substr(i, 4);
var decimal = parseInt(bytes, 2); // convert to dec then hex
var hex = decimal.toString(16);

output += hex;
output = hex + output;
}

var rest = binaryString.length % 4;

if(rest != 0) {
var bytes = binaryString.substr(0, rest);
var decimal = parseInt(bytes, 2);

output = decimal.toString(16) + output;
}

return output.replace(/[^\dA-Za-z]/g, "").replace(/(.{2})/g, "$1 ").trim();
return output.toUpperCase();
},

/**
Expand Down

0 comments on commit 928eb99

Please sign in to comment.