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

Commit 928eb99

Browse files
vonakamoollaza
authored andcommitted
Text Converter: Fix binary conversion bug. (#4526)
* Fix binary-to-decimal and binary-to-hexadecimal conversion bug. * Lazy #4566 fix.
1 parent c04f35c commit 928eb99

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

share/goodie/text_converter/text_converter.js

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ DDH.text_converter = DDH.text_converter || {};
1010
$convert_selects,
1111
$convert_from_select,
1212
$convert_to_select,
13-
$convert_from_textarea,
13+
$convert_from_textarea,
1414
$convert_to_textarea;
1515

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

32-
if(from_type === "binary" && to_type === "hexadecimal") {
32+
if(from_type === "decimal" && to_type === "binary") {
33+
return parseInt(from, 10).toString(2);
34+
35+
} else if(from_type === "binary" && to_type === "hexadecimal") {
3336
return TextConverter.binaryToHex(from);
3437

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

131134
binaryToDecimal: function(binary) {
132-
var octet = binary.replace(/\s/g, "").match(/.{1,8}/g);
133-
var dec_cache = [];
134-
135-
for(var i = 0; i < octet.length; i++) {
136-
dec_cache.push(parseInt(octet[i], 2));
137-
}
138-
139-
return dec_cache.join(" ");
135+
binary = binary.replace(/\s+/g, "");
136+
return parseInt(binary, 2);
140137
},
141138

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

148145
binaryToHex: function(binaryString) {
149-
var binaryString = binaryString.replace(/\s/g, "");
146+
var binaryString = binaryString.replace(/\s+/g, "");
150147
var output = "";
151148

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

158-
output += hex;
155+
output = hex + output;
156+
}
157+
158+
var rest = binaryString.length % 4;
159+
160+
if(rest != 0) {
161+
var bytes = binaryString.substr(0, rest);
162+
var decimal = parseInt(bytes, 2);
163+
164+
output = decimal.toString(16) + output;
159165
}
160166

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

164170
/**

0 commit comments

Comments
 (0)