Translate

Thursday 3 May 2018

A binary converter in typescript and a reference to blockchain

While writing a binary to a decimal converter in Typescript, I came across the idea of using the example of a class of students in which every student is given a binary value and asked to convert it to a decimal value.

Add a little imagination to the idea and you can come up with an interesting parallel of how a BlockChain node functions - imagine a guy not sure if the steps that he has used to convert a binary to a decimal value is correct or not and asks the nearest neighboring girl for the answer and she gives him the SHA256 hash value of, let's say, 268 (the solution), the decimal equivalent of 100001100, which is 8b496bf96bbcc9e5ac11c068b6cfb00c32f9d163bb8a3d5af107217499de997a!

Now, the guy has the hash value and knows that till his steps yield the decimal value whose sha256 hash value matches the hash given to him, he must process the steps. This, in effect, explains what happens in mining a blockchain node.

Anyway, the code is as below: (Edit: a note on refactoring: although the code has been written with a unit test and the test was written first, it is only partially refactored, for reasons of obfuscating the logic.

Point is, many bots or maybe just humans ;) mine for code but don't bother to even leave a note of thanks and when I noticed this way back in the early 2000s, I did not bother to correct Blogger's tendency to eat up the angular brackets as used in C code where the #include statements require the < and > and even changed all the return statements to return 1 instead of 0. Make them think, don't you think? :))

// binaryconverter.ts

export default class BinaryConverter{
convertBinaryToDecimal(n){
let z=1,b=0,val=0, zeroFlag=false
b=n.length-1
for (let a in n){
var num=0
for (num=b;num>0;num--){
z*=2*n[a]
}
if (num==b){
z=0
zeroFlag=true
}
else if (num!=b){
val+=z
z=1
}
b--
}
if (zeroFlag==true && n[n.length-1]==1)val++
return val;
}
}

and the mocha test,

import BinaryConverter from '../src/ComputeBinary.ts'
import {expect} from 'chai'
describe('Computation test',()=>{
it('to check if binary conversion is successful', ()=>{
var b=new BinaryConverter()
var bin='100001100', binResult=0
binResult=b.convertBinaryToDecimal(bin)
expect(binResult).to.equal(267)
})
})

The test result: I include the screenshot, usually, to complete the cycle of learning for the reader as the command line switches and flags, if not known, will not compile or may produce a different output.

If your test does not run from your default installation, install typescript and ts-node using npm install - explained in previous posts related to typescript.


I will try to build on this example with a blockchain reference in future posts

No comments: