Languages
[Edit]
EN

Java - convert binary String to long

13 points
Created by:
Root-ssh
157970

Short solution:

String binaryString = "00111111111111111101111111111111111111111";
long number = Long.parseLong(binaryString, 2);

System.out.println(number); // 549751619583

The best way to convert binary String to long in java is to use Long.parseLong() method.

Syntax:

Long.parseLong(String binaryString, int radix)

1. Simple example

public class Example1 {

    public static void main(String[] args) {

        String binaryString = "00111111111111111101111111111111111111111";
        long number = Long.parseLong(binaryString, 2);
        System.out.println(number); // 549751619583
    }
}

Output:

549751619583

2. Convert couple of different binary strings to long

public class Example2 {

    public static void main(String[] args) {

        System.out.println( Long.parseLong("00000000", 2) ); // 0
        System.out.println( Long.parseLong("00000101", 2) ); // 5
        System.out.println( Long.parseLong("00001000", 2) ); // 8
        System.out.println( Long.parseLong("00001100", 2) ); // 12
        System.out.println( Long.parseLong("00010000", 2) ); // 16
        System.out.println( Long.parseLong("11111111", 2) ); // 255

        String maxLong = "01111111111111111111111111111111" +
                         "11111111111111111111111111111111";
        System.out.println( Long.parseLong(maxLong, 2) ); // 9223372036854775807
        System.out.println( Long.MAX_VALUE );             // 9223372036854775807
    }
}

Output:

0
5
8
12
16
255
9223372036854775807
9223372036854775807

3. Convert binary string to long in loop - from 0 to 16

In this example we convert binary string to long in loop from 0 to 16 and then we print both binary and long representations of given number.

public class Example3 {

    public static void main(String[] args) {

        for (long number = 0; number <= 16; number++) {

            String binaryString = Long.toBinaryString(number);

            String format = String.format("%8s", binaryString);
            String withLeadingZeros = format.replace(' ', '0');

            long backToNumber = Long.parseLong(binaryString, 2);

            System.out.println(withLeadingZeros + " - " + backToNumber);
        }
    }
}

Output:

00000000 - 0
00000001 - 1
00000010 - 2
00000011 - 3
00000100 - 4
00000101 - 5
00000110 - 6
00000111 - 7
00001000 - 8
00001001 - 9
00001010 - 10
00001011 - 11
00001100 - 12
00001101 - 13
00001110 - 14
00001111 - 15
00010000 - 16

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join