• + 0 comments

    TypeScript binary converter function (The hard way lol)

    function binary_convert(n:number):string{
        let i:number = 0;
        let binary:string = '';
        let max:number = 0;
        
        
        while(Math.pow(2,i)<n){
            //Save the largest number for considering total length of binary
            max = i+1;
            i++;    
        }
        
        // console.log(i);
                
        // Divide it until every element is turned to binary (No remainder left)
        while(n>0 && i > 0){
                // Binary is larger or equal to remainder, modulo and add 1 to the binary string
                if(Math.pow(2,i-1)<= n){
                    n = n%Math.pow(2,i-1);
                    binary += '1';
                }
                // Number bigger than largest binary : skip the current binary
                else{
                   binary += '0'; 
                }
                
            // Continue to smaller binary
            i--;
            }
        
        // console.log('max  =' + max)
        
        // If no remainder left, Add zeroes at the right until full length
        while(binary.length < max){
            binary += '0';
        }
        // console.log('binary = ' + binary)
        return binary
    }