How to convert Parse ObjectId (String) to long?

Each object has its own Parse.com ObjectId, which is a char line 10 and, apparently, this creates a regular expression [0-9a-zA-Z]{10}.

Parse ObjectId example:

  • X12wEq4sFf
  • Weg243d21s
  • zwg34GdsWE

I would like to convert this string to Long, because it will save memory and improve the search. (10 characters using UTF-8 are 40 bytes and 1 is 8 bytes long)

If we calculate the combinations, we can find:

  • String ObjectId: 62 ^ 10 = 839299365868340224 different values;
  • long: is 2 ^ 64 = 18446744073709551616 different values.

Thus, we can convert these values ​​without loss of information. Is there an easy way to do this safely? Please consider any encoding for Chars (UTF-8, UTF-16, etc.);

EDIT: I just think this is hard to solve. I ask if there is an easy way.

+4
source share
2 answers
  • Your character set is a subset of the widely used Base64 encoding, so you can just use this. Java has a Base64 class , so you do not need to download your own codec for this.
  • , ? " " ; , - .

EDIT: , UTF-8 -ascii? 10 char byte[10], 10 40 ( 8 a long). - .

+5

, 6 .

public class Converter {

    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

    private static int convertChar(char c) {
        int ret = CHARS.indexOf( c );
        if (ret == -1)
            throw new IllegalArgumentException( "Invalid character encountered: "+c);
        return ret;
    }

    public static long convert(String s) {
        if (s.length() != 10)
            throw new IllegalArgumentException( "String length must be 10, was "+s.length() );
        long ret = 0;
        for (int i = 0; i < s.length(); i++) {
            ret = (ret << 6) + convertChar( s.charAt( i ));
        }
        return ret;
    }
}

long String , .

P.s.: , long, long, .

Ps 2: , : ASCII 10 , long 4. , , d , 10 .

+1

Source: https://habr.com/ru/post/1589502/


All Articles