我有此分配,我在此向用户询问消息,然后它必须将该文本转换为十进制,然后将该十进制转换为二进制,然后返回二进制数。他们给了我所有的功能,除了将文本转换为十进制的功能。我什至无法开始思考如何在不编写充满字符的整个数组的情况下进行此操作。
代码如下:
/*
* This program encodes user input into binary data!
* Your job is to write the textToBinary function
*/
function start()
{
var text = readLine("Input the string you would like to encode: ");
var binary = textToBinary(text);
println(binary);
}
function textToBinary(text)
{
// Write this method!
// For every character in the text,
// convert the character into its ASCII decimal encoding
// then convert that decimal value into its equivalent binary encoding
// and combine each binary encoding to get the resulting binary string
}
// Converts a given decimal value into an 8 bit binary value
function decimalToBinary(decimalValue)
{
var binaryBase = 2;
var numBitsDesired = 8;
var binaryValue = decimalValue.toString(binaryBase);
while(binaryValue.length < numBitsDesired)
{
binaryValue = "0" + binaryValue;
}
return binaryValue;
}