Is it possible to base 36 encode with JavaScript / jQuery?

后端 未结 4 2047
臣服心动
臣服心动 2021-01-31 18:00

I\'m thinking about using the encode/decode technique here (Encoding to base 36/decoding from base 36 is simple in Ruby)

how to implement a short url like urls in twitte

4条回答
  •  长情又很酷
    2021-01-31 18:25

    For anyone looking to decode @imjosh's answer in python (say if you've encoded client-side and need to decode server-side), this is what I used. I would have left as a comment in @imjosh's answer but comments don't format very well.

    def decodeBase36(str):
      decoded_str = ""
      for i in range(0, len(str), 2):
        char = chr(int(str[i:i+2], 36))
        decoded_str += char
      return decoded_str
    

    and a not-as-elegant Objective-C version:

    + (NSString *)b36DecodeString:(NSString *)b36String
    {
        NSMutableString *decodedString = [NSMutableString stringWithFormat:@""];
        for (int i = 0; i < [b36String length]; i+=2) {
            NSString *b36Char = [b36String substringWithRange:NSMakeRange(i, 2)];
            int asciiCode = 0;
            for (int j = 0; j < 2; j++) {
                int v = [b36Char characterAtIndex:j];
                asciiCode += ((v < 65) ? (v - 48) : (v - 97 + 10)) * (int)pow(36, 1 - j);
            }
            [decodedString appendString:[NSString stringWithFormat:@"%c", asciiCode]];
        }
        return decodedString;
    }
    

提交回复
热议问题