JSFiddle - React, Tailwind, and code Playground
by darul75
HTML
Example for combining bytes into numbers. <br><br>
Imagine these 2 following bytes : 10000001 00000001<br><br>
How can we combine them to get corresponding number in javascript ?<br><br>
- Idea is to take first byte : 10000001<br><br>
- Shift its bits to the left giving 10000001 00000000<br><br>
- Apply OR Bitwise with second byte 00000001<br><br>
- Ok now we have our number 10000001 00000000 | 00000001 == 10000001 00000001<br><br>
<div>
Byte 1 <input type="number" id="1" placeholder="type num" /></br>
Byte 2 <input type="number" id="2" placeholder="type num"/></br>
Byte 3 <input type="number" id="3" placeholder="type num"/></br>
Byte 4 <input type="number" id="4" placeholder="type num"/></br>
<input type="submit" id="sum" value="do"></input>
</br>
</br>
Each in binary representation
</br>
Byte 1 <label id="label1"></label></br>
Byte 2 <label id="label2"></label></br>
Byte 3 <label id="label3"></label></br>
Byte 4 <label id="label4"></label></br>
</br>
</br>
Using bit shifting to add them
</br>
sum of 2:<label id="sum1"></label>
</br>
sum of 3:<label id="sum2"></label>
</br>
sum of 4:<label id="sum3"></label>
</br>
</div>
JavaScript
var num1, num2, num3, num4;
function concat2(a, b){
return (a << 8) | b;
}
function concat3(a, b, c){
return (a << 16) | (b << 8) | c;
}
function concat4(a, b, c, d){
return (a << 24) | (b << 16) | (c << 8) | d;
}
function doConcat() {
console.log($('#value1').val());
}
$( "input[type='number']" ).change(function(e) {
var id = e.target.id;
var value = e.target.value;
eval('num'+id+' = ' + value);
$('#label'+id).html(ConvertBase.dec2bin(value));
if (num1 && num2) {
$('#sum1').html(ConvertBase.dec2bin(concat2(num1,num2)));
}
if (num1 && num2 && num3) {
$('#sum2').html(ConvertBase.dec2bin(concat3(num1,num2, num3)));
}
if (num1 && num2 && num3 && num4) {
$('#sum3').html(ConvertBase.dec2bin(concat4(num1,num2, num3, num4)));
}
});
$('#sum').click( function() {
doConcat();
});
// UTILS
(function(){
var ConvertBase = function (num) {
return {
from : function (baseFrom) {
return {
to : function (baseTo) {
return parseInt(num, baseFrom).toString(baseTo);
}
};
}
};
};
// binary to decimal
ConvertBase.bin2dec = function (num) {
return ConvertBase(num).from(2).to(10);
};
// binary to hexadecimal
ConvertBase.bin2hex = function (num) {
return ConvertBase(num).from(2).to(16);
};
// decimal to binary
ConvertBase.dec2bin = function (num) {
return ConvertBase(num).from(10).to(2);
};
// decimal to hexadecimal
ConvertBase.dec2hex = function (num) {
return ConvertBase(num).from(10).to(16);
};
// hexadecimal to binary
ConvertBase.hex2bin = function (num) {
return ConvertBase(num).from(16).to(2);
};
// hexadecimal to decimal
ConvertBase.hex2dec = function (num) {
return...