Solved

# Java Long variabel type conversion

Posted on 2006-05-09
Medium Priority
298 Views
How can I convert the string '12345678901' into type long.

or

how can I get testx to equal 12345678901L (long)

StringBuffer serial_b = new StringBuffer( Long.toBinaryString(testx) );

Thak You
0
Question by:cottyengland

LVL 17

Expert Comment

ID: 16645009
Hi cottyengland,

Try:
long longPrimative = Long.parseLong("12345678901");

Joe P
0

LVL 17

Accepted Solution

BogoJoker earned 2000 total points
ID: 16645021
Full program, compile and run:
{
public static void main(String[] args)
{
// Create a long from a string
long testx = Long.parseLong("12345678901");

// Then put it into the buffer
StringBuffer serial_b = new StringBuffer( Long.toBinaryString(testx) );

// Print
System.out.println(serial_b);
}
}

Joe P
0

LVL 23

Expert Comment

ID: 16645220
long testx = Long.parseLong("12345678901");

you need to handle NumberFormatException
0

LVL 14

Expert Comment

ID: 16645242
Obviously if the integer is bigger than is able to fit in a long, you will have to use BigInteger:

BigInteger veryBigNumber = new BigInteger("123456789011234567890112345678901");
String binaryString = veryBigNumber.toString(2);
0

LVL 14

Expert Comment

ID: 16645249
Actually, you can use the above code for any size integer.
0

LVL 23

Expert Comment

ID: 16645396
Hi,

public class s2l {

public static void main (String[] args) {

// String s = "fred";    // do this if you want an exception

String s = "12345678901";

try {
long l = Long.parseLong(s.trim());
System.out.println("long l = " + l);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}

}

}

R.K
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
###### Suggested Courses
Course of the Month16 days, 17 hours left to enroll