0

I'm working on a piece of code to turn text to binary. First, I turn the text to decimal, then the decimal to binary. The problem I'm getting, is in the 'decimalToBinary' function, it is telling me "Uncaught TypeError: Cannot read property 'toString' of undefined", could someone explain what's wrong?

function start() {
    var text = readLine("Input the string you would like to encode: ");
    var binary = textToBinary(text);
    println(binary);
}

function textToBinary(text) {
    var toASCII = [];
    var toBINARY = [];
    text.toUpperCase();
    for (var i = 0; i < text.length; i++) {
        var ASCII_CODE = text.charCodeAt(i);
        toASCII.push(ASCII_CODE);
    }
    for (var j = 0; j < toASCII.length; i++) {
        var arrnum = toASCII[i]
        var final = decimalToBinary(arrnum);
        toBINARY.push(final);
    }
    return toBINARY;
}

function decimalToBinary(decimalValue) {
    var binaryBase = 2;
    var numBitsDesired = 8;
    var binaryValue = decimalValue.toString(binaryBase);
    while (binaryValue.length < numBitsDesired) {
        binaryValue = "0" + binaryValue;
    }
    return binaryValue;
}
0

1 Answer 1

2

You've some typos in your code:

function textToBinary(text){
    var toASCII = [];
    var toBINARY = [];
    text.toUpperCase();
    for(var i = 0 ; i < text.length ; i++){
        var ASCII_CODE = text.charCodeAt(i);
        toASCII.push(ASCII_CODE);
    }
    for(var j = 0 ; j < toASCII.length ; i++){ // <- This should be j++ instead of i++
        var arrnum = toASCII[i] // <- Same here; j instead of i (i is off limits).
        var final = decimalToBinary(arrnum);
        toBINARY.push(final);
    }
    return toBINARY;
}

By accessing an array with an invalid index (out of bounds), you're getting an undefined value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That always seems to be my problem when I use two for loops in the same function!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.