-
Notifications
You must be signed in to change notification settings - Fork 0
/
binhex.js
122 lines (100 loc) · 2.33 KB
/
binhex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
'use strict';
var $=require('jquery');
var bigInt=require('big-integer');
$('tr').click(function()
{
//Clicking anywhere in a row highlights that row's input
$('textarea', this).focus();
});
function doConversions(value, base)
{
//If value is blank, just clear everything
if(value==='')
{
$('#bin, #hex, #dec, #octal').val('').css({'height':'auto'});
return;
}
var bi=bigInt(value, base);
//Binary
if(base!=2)
{
$('#bin').val(formatBin(bi.toString(2)));
resizeTextarea($('#bin'));
}
//Hexadecimal
if(base!=16)
{
$('#hex').val(formatHex(bi.toString(16)));
resizeTextarea($('#hex'));
}
//Decimal
if(base!=10)
{
$('#dec').val(formatDec(bi.toString(10)));
resizeTextarea($('#dec'));
}
//Octal
if(base!=8)
{
$('#octal').val(formatOctal(bi.toString(8)));
resizeTextarea($('#octal'));
}
}
function formatBin(bin)
{
return bin.replace(/(.)(?=(.{8})+$)/g, '$1 ');
}
function formatHex(hex)
{
return hex.replace(/(.)(?=(.{2})+$)/g, '$1 ');
}
function formatDec(dec)
{
return dec.replace(/(.)(?=(.{3})+$)/g, '$1,');
}
function formatOctal(octal)
{
return octal;
}
function resizeTextarea(textarea)
{
textarea.css({'height':'auto'}).height(textarea.get(0).scrollHeight);
}
//Handle binary input
$('#bin').on('input', function()
{
//Remove non-binary characters
var text=$(this).val().replace(/[^0-1]/g,'');
doConversions(text, 2);
$(this).val(formatBin(text));
resizeTextarea($(this));
});
//Handle hexadecimal input
$('#hex').on('input', function()
{
//Remove non-hexadecimal characters
var text=$(this).val().replace(/[^0-9a-fA-F]/g,'');
doConversions(text, 16);
$(this).val(formatHex(text));
resizeTextarea($(this));
});
//Handle decimal input
$('#dec').on('input', function()
{
//Remove non-decimal characters
var text=$(this).val().replace(/[^0-9]/g,'');
doConversions(text, 10);
$(this).val(formatDec(text));
resizeTextarea($(this));
});
//Handle octal input
$('#octal').on('input', function()
{
//Remove non-octal characters
var text=$(this).val().replace(/[^0-7]/g,'');
doConversions(text, 8);
$(this).val(formatOctal(text));
resizeTextarea($(this));
});
//Auto-focus binary field
$('#bin').focus();