1

I'm looking for a better way to convert an int to 64 bit binary represented as String. Right now I'm converting int to 32bit binary and then adding 32 zeroes in front of it. I'm implementing SHA-1 and I need that int to be 64bit binary.

private static String convertIntTo64BitBinary(int input) {
    StringBuilder convertedInt = new StringBuilder();
    for(int i = 31; i >= 0; i--) { // because int is 4 bytes thus 32 bits
        int mask = 1 << i;
        convertedInt.append((input & mask) != 0 ? "1" : "0");
    }
    for(int i = 0; i < 32; i++){
        convertedInt.insert(0, "0");
    }
    return convertedInt.toString();
}

EDIT 1: Unfortunately this doesn't work:

    int messageLength = message.length();
    String messageLengthInBinary = Long.toBinaryString((long) messageLength);

messageLengthInBinary is "110"

EDIT 2: To clarify: I need the string to be 64 chars long so need all the leading zeros.

ohwelppp
  • 2,029
  • 2
  • 25
  • 45
  • 3
    why not just use a `long` instead of an `int` and why not just use [toBinaryString](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int)) ? – luk2302 Jun 23 '17 at 10:15
  • It's not working - check my EDIT 1. I need the leading zeros to make it 64 bit long. – ohwelppp Jun 23 '17 at 10:29

1 Answers1

3

You could use the long datatype which is a 64 bit signed integer. Then calling Long.toBinaryString(i) would give you the binary representation of i

If you already have an int then you could cast it to a long and use the above.

This doesn't include the leading 0s so the resulting string needs padding to the 64 characters. Something like this would work.

String value = Long.toBinaryString(i)
String zeros = "0000000000000000000000000000000000000000000000000000000000000000" //String of 64 zeros
zeros.substring(value.length()) + value;

See How can I pad a String in Java? for more options.

The_Lone_Devil
  • 496
  • 11
  • 15
  • It's not working unfortunately - tried it before. Look at my edit – ohwelppp Jun 23 '17 at 10:23
  • @doublemc Ahhh its because it doesn't include the leading `0`s. You would need to pad the string with them yourself, give me a couple of mins to whip up an edit – The_Lone_Devil Jun 23 '17 at 10:26
  • Yeah, I've got it working as stated in the post but it's so ugly (using SB's insert) that I'm looking for some other approach. – ohwelppp Jun 23 '17 at 10:29