如何将字母转换为二进制代码?

时间:2016-05-19 04:56:05

标签: javascript

// # Write a method that takes in an integer `offset` and a string.
// # Produce a new string, where each letter is shifted by `offset`. You
// # may assume that the string contains only lowercase letters and
// # spaces.
// #
// # When shifting "z" by three letters, wrap around to the front of the
// # alphabet to produce the letter "c".
// #
// # You'll want to use String's `ord` method and Integer's `chr` method.
// # `ord` converts a letter to an ASCII number code. `chr` converts an
// # ASCII number code to a letter.
// #
// # You may look at the ASCII printable characters chart:
// #
// #     http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
// #
// # Notice that the letter 'a' has code 97, 'b' has code 98, etc., up to
// # 'z' having code 122.
// #
// # You may also want to use the `%` modulo operation to handle wrapping
// # of "z" to the front of the alphabet.
// #
// # Difficulty: hard. Because this problem relies on outside
// # information, we would not give it to you on the timed challenge. :-)
//
// def caesar_cipher(offset, string)
// end
//
// # These are tests to check that your code is working. After writing
// # your solution, they should all print true.
//
// puts(
//   'caesar_cipher(3, "abc") == "def": ' +
//   (caesar_cipher(3, 'abc') == 'def').to_s
// )
// puts(
//   'caesar_cipher(3, "abc xyz") == "def abc": ' +
//   (caesar_cipher(3, 'abc xyz') == 'def abc').to_s
// )    



    function caesar_cipher(offset,string){
        var strSplit = string.split(" ");
        var result =[];
        var str = "";

         strSplit.forEach(function(word){
           for(var j=0;j<word.length;j++){
            result.push(word[j].charCodeAt(0)); // returns 65
           }
         });

         for(var idx =0;idx<result.length;idx++){
           if(result[idx] ===122 || (result[idx]+offset) ===122){
             str += String.fromCharCode((97+ offset));

           }else{
            str += String.fromCharCode((result[idx]+ offset));
           } 
         }
        return str;
        }
        console.log(caesar_cipher(3,"abc xyz"));

我怎样才能解决这样的情况: 如果字母代码是121,偏移量是3,等于= 124; 我怎样才能绕到字母表的前面?

2 个答案:

答案 0 :(得分:0)

提示:

您可以通过

获取角色的ascii代码
var asciiCode = "a".charCodeAt(0); //removing 0 will give the same output

然后你可以添加偏移量

var newAsciiCode = asciiCode + 3; //3 is offset

然后收回你的新信件

var newLetter = String.fromCharCode( newAsciiCode );

答案 1 :(得分:0)

字母表在JavaScrip中使用,如ASCII中所定义。应该做以下所有转变:https://en.wikipedia.org/wiki/ASCII

如果您有122 +偏移量超过ASCII限制的情况,那么如果您想将其向上舍入以回到ASCII的前面:

只需将96添加到当前(ASCII代码%122)。它将在96-122之间回归。 例如,假设偏移量为3;你当前的字母ASCII码是122;在这里

(123 + 96)%122 = 97这是&#34; a&#34;