1

I want to hash a word into fixed bit hash value say 64 bit,32 bit (binary).

I used the following code

   long murmur_hash= MurmurHash.hash64(word);

Then murmur_hash value is converted into binary by the following function

   public static String intToBinary (int n, int numOfBits) {
        String binary = "";
        for(int i = 0; i < numOfBits; ++i) {
           n/=2;
           if(n%2 == 0)
              {
               binary="0"+binary;
              }
           else
               binary="1"+binary;
         }

     return binary;
   }

Is there any direct hash method to convert into binary?

1
  • You can use Integer.toBinaryString(int) Commented Jul 16, 2015 at 7:40

3 Answers 3

1

Just use this

Integer.toBinaryString(int i)
Sign up to request clarification or add additional context in comments.

1 Comment

But the returned value is long ..is there any problem to use your code by cast long into int
0

If you want to convert into a fixed binary string, that is, always get a 64-character long string with zero padding, then you have a couple of options. If you have Apache's StringUtils, you can use:

StringUtils.leftPad( Long.toBinaryString(murmurHash), Long.SIZE, "0" );

If you don't, you can write a padding method yourself:

public static String paddedBinaryFromLong( long val ) {
    StringBuilder sb = new StringBuilder( Long.toBinaryString(val));
    char[] zeros = new char[Long.SIZE - sb.length()];
    Arrays.fill(zeros, '0');
    sb.insert(0, zeros);
    return sb.toString();
}

This method starts by using the Long.toBinaryString(long) method, which conveniently does the bit conversion for you. The only thing it doesn't do is pad on the left if the value is shorter than 64 characters.

The next step is to create an array of 0 characters with the missing zeros needed to pad to the left.

Finally, we insert that array of zeros at the beginning of our StringBuilder, and we have a 64-character, zero-padded bit string.


Note: there is a difference between using Long.toBinaryString(long) and Long.toString(long,radix). The difference is in negative numbers. In the first, you'll get the full, two's complement value of the number. In the second, you'll get the number with a minus sign:

    System.out.println(Long.toString(-15L,2));

result:

-1111
    System.out.println(Long.toBinaryString(-15L));

result:

1111111111111111111111111111111111111111111111111111111111110001

Comments

0

Another other way is using

Integer.toString(i, radix)

you can get string representation of the first argument i in the radix ( Binary - 2, Octal - 8, Decimal - 10, Hex - 16) specified by the second argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.