سؤال

I'm using LevelDB from Java via JNI.

I want to supply a numeric (integer) key, and be able to iterate the db in the order of that key. Where I'm having difficulty is understanding how LevelDb's default comparator actually works, and how I would encode an int into a byte[] that would let the default comparator correctly order by that int.

The LevelDb doco states:

The preceding examples used the default ordering function for key, which orders bytes lexicographically.

I've googled around but am stumped for how I would actually encode an int into lexicographically ordered bytes?

Note: If I supply my own comparator, it roughly doubles iteration time as now all the comparisons have to jump back and forth over the JNI boundary, so I don't want to do that.

هل كانت مفيدة؟

المحلول

This encoding works:

public synchronized static byte[] encode(int key) {
        encoded[0] = (byte)(key >> 24);
        encoded[1] = (byte)(key >> 16);
        encoded[2] = (byte)(key >> 8);
        encoded[3] = (byte)(key);
        return encoded;
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top