Hints on writing strToNum and numToStr

listToNum

Write a function listToNum so that listToNum b x takes a base b and a list of integer digits x, and produces the number that x represents as a base b number. For example, listToNum 10 [9,4,2] = 942, listToNum 10 [5,3,7,6] = 5376 and listToNum 2 [1,1,0,0] = 12. Test listToNum. [Hint on listToNum]

strToNum

Now write a function strToNum so that strToNum(s) is a number that string s represents.

A string is a list of characters. Each character has a code, which is a natural number. Function rank will give you the code of a character. For example, rank('a') = 97. If you map rank onto a string, you get a list of numbers. For example, map rank "abc" = [97, 98, 99].

Start by writing strToNum so that it uses a function called myRank in place of rank. Make myRank take a decimal digit and convert it to a number. For example, myRank('3') = 3. You can define it by myRank(c) = rank(c) -- rank('0'). Now write strToNum so that strToNum("352") = 352. Test this version of strToNum.

But the characters in our strings are not necessarily decimal digits. They might conceivably be any value that can be put into a byte. (We might even be asked to encipher a binary file.) An obvious thing to do is just to redefine myRank to be the same as rank, and to use base 256 instead of base 10. That idea is close, but it has a problem. Notice that listToNum 10 [0,1] is the same as listToNum 10 [1]. Leading zeros are ignored. But that means that it is impossible to recover the original list from the number. If all you have is the number 1, how do you know whether it came from list [1] or from list [0,1] or [0,0,1], etc.? You can avoid this problem by ensuring that the number 0 does not occur in the list. So define myRank(c) = rank(c) + 1.

With the new definition of myRank, you can handle any byte, but you must work in base 257 instead of 256. Modify your strToNum function to work in base 257 with this new myRank function.

numToList and numToStr

You will also need to convert back from a number to a string. Write a function numToStr so that numToStr(strToNum(s)) = s. That is, numToStr does the inverse transformation of strToNum. The main part of this is a function numToList so that (numToList b n) produces the list of digits represented by number n, in base b, without any leading zeros. For example, numToList 10 942 = [9,4,2]. [Hint for numToList]