Logic of converting strings to integer
Hi all,
I know that , I can convert a string into a number using API , Ineger.parseInt() . But i want to know the reall algoritham behind that
.Can anybody explane that ?
Basically I am interested in
String s = "123";
int i = Integer.parseInt(s);
But i want to know what is the logic running behind this ?. Can anybody please help me. ...?
Thanks in advance....
The decompiled version parseInt() from Integer class
* Parses the string argument as a signed decimal integer. The
* characters in the string must all be decimal digits, except that
* the first character may be an ASCII minus sign <code>'-'</code>
* (<code>'\u002D'</code>) to indicate a negative value. The resulting
* integer value is returned, exactly as if the argument and the radix
* 10 were given as arguments to the
* {@link #parseInt(java.lang.String, int)} method.
* @param s a <code>String</code> containing the <code>int</code>
* representation to be parsed
* @return the integer value represented by the argument in decimal.
* @exception NumberFormatException if the string does not contain a
* parsable integer.
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
* Parses the string argument as a signed integer in the radix
* specified by the second argument. The characters in the string
* must all be digits of the specified radix (as determined by
* whether {@link java.lang.Character#digit(char, int)} returns a
* nonnegative value), except that the first character may be an
* ASCII minus sign <code>'-'</code> (<code>'\u002D'</code>) to
* indicate a negative value. The resulting integer value is returned.
* <p>
* An exception of type <code>NumberFormatException</code> is
* thrown if any of the following situations occurs:
* <ul>
* <li>The first argument is <code>null</code> or is a string of
* length zero.
* <li>The radix is either smaller than
* {@link java.lang.Character#MIN_RADIX} or
* larger than {@link java.lang.Character#MAX_RADIX}.
* <li>Any character of the string is not a digit of the specified
* radix, except that the first character may be a minus sign
* <code>'-'</code> (<code>'\u002D'</code>) provided that the
* string is longer than length 1.
* <li>The value represented by the string is not a value of type
* <code>int</code>.
* </ul><p>
* Examples:
* <blockquote><pre>
* parseInt("0", 10) returns 0
* parseInt("473", 10) returns 473
* parseInt("-0", 10) returns 0
* parseInt("-FF", 16) returns -255
* parseInt("1100110", 2) returns 102
* parseInt("2147483647", 10) returns 2147483647
* parseInt("-2147483648", 10) returns -2147483648
* parseInt("2147483648", 10) throws a NumberFormatException
* parseInt("99", 8) throws a NumberFormatException
* parseInt("Kona", 10) throws a NumberFormatException
* parseInt("Kona", 27) returns 411787
* </pre></blockquote>
* @param s the <code>String</code> containing the integer
* representation to be parsed
* @param radix the radix to be used while parsing <code>s</code>.
* @return the integer represented by the string argument in the
* specified radix.
* @exception NumberFormatException if the <code>String</code>
* does not contain a parsable <code>int</code>.
public static int parseInt(String s, int radix)
throws NumberFormatException
if (s == null) {
throw new NumberFormatException("null");
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;
if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
multmin = limit / radix;
if (i < max) {
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
} else {
result = -digit;
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
if (result < multmin) {
throw NumberFormatException.forInputString(s);
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
result -= digit;
} else {
throw NumberFormatException.forInputString(s);
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw NumberFormatException.forInputString(s);
} else {
return -result;
}
Similar Messages
-
package onjava;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
import java.lang.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CalcClient extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"");
out.println("\"http://www.w3.org/TR/html4/loose.dtd\">");
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
out.println("<title>Substraction using SOAP</title>");
out.println("</head>");
URL url = new URL ("http://localhost/soap/servlet/rpcrouter");
Integer p1=request.getParameter("param1");
Integer p2=request.getParameter("param2");
In the above statement i have to convert the string to integer because that has to be passed in my program as an argument to a function so please let me know how to do that
// Build the call.
Call call = new Call();
call.setTargetObjectURI("urn:onjavaserver");
call.setMethodName("subtract");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector params = new Vector();
params.addElement(new Parameter("p1", Integer.class, p1, null));
params.addElement(new Parameter("p2", Integer.class, p2, null));
call.setParams (params);
// make the call: note that the action URI is empty because the
// XML-SOAP rpc router does not need this. This may change in the
// future.
Response resp = call.invoke(url, "" );
// Check the response.
if ( resp.generatedFault() ) {
Fault fault = resp.getFault ();
out.println("The call failed: ");
out.println("Fault Code = " + fault.getFaultCode());
out.println("Fault String = " + fault.getFaultString());
else {
Parameter result = resp.getReturnValue();
out.println(result.getValue());
out.println("</body>");
out.println("</html>");Two possibilities: Try either java.lang.Integer.valueOf() or java.text.NumberFormat and its parse method.
Either one will do what you want. I think Integer will be the simpler of the two.
The code you have is obviously not correct, because getParameter returns a String:
Integer p1=request.getParameter("param1");Do it like this:
Integer p1=Integer.valueOf(request.getParameter("param1"));% -
Converting String to integer?
I looked on the sun forums and only found a lot of things that convert integers to Strings. Nothing to do the opposite.
Does anyone know how I can convert a String to an int?coopkev2 wrote:
an "A" from a "B"?? I don't understand what you are saying... I want to convert "100" to 100.
Edit-- I'll be back soon.Read "A" as "Integer" and "B" as "String".
In this case: read the [java.lang.Integer API|http://java.sun.com/javase/6/docs/api/java/lang/Integer.html] if there is a method which takes a String and returns an Integer or int. -
Beginner ?: Converting String to Integer
Hello! I'm having some trouble converting a string to an integer. Here is my code:
var str:String = e.currentTarget.name as String; // Getting values like "song1", "song2"
str = str.replace("song", ""); // Changes it from "song1" or "song2" to "1" or "2"
var num:int = str as int; // SHOULD be converting the "1" to 1 and "2" to 2
trace("num:" + num + ", str:" + str);
The trace is always outputting:
num:0, str:1
num:0, str:2
etc..
The str value is there, but when it gets put into num then it zeros out. What am I doing wrong?
Thanks in advance!Try using: var num:int = int(str);
-
Typecasting string to integer. need help
Hi,
I have the following statement which returns a String but i need to convert to an integer .
properties.getProperty("MAXWIDTH");
Can i do it this way,
int width = (Integer) properties.getProperty("MAXWIDTH");
But it gives me error stating that it cannot convert string to integer.
Please help
PurnimaThat's because the value returned from the
getProperty() method is a String. You can convert it
to an int, like this:int width =
Integer.parseInt(properties.getProperty("MAXWIDTH"));[
/code]oh so simple thanks
Purnima -
How to convert string to an integer in SQL Server 2008
Hi All,
How to convert string to an integer in sql server,
Input : string str="1,2,3,5"
Output would be : 1,2,3,5
Thanks in advance.
Regards,
SunilNo, you cannot convert to INT and get 1,2,3 BUT you can get
1
2
3
Is it ok?
CREATE FUNCTION [dbo].[SplitString]
@str VARCHAR(MAX)
RETURNS @ret TABLE (token VARCHAR(MAX))
AS
BEGIN
DECLARE @x XML
SET @x = '<t>' + REPLACE(@str, ',', '</t><t>') + '</t>'
INSERT INTO @ret
SELECT x.i.value('.', 'VARCHAR(MAX)') AS token
FROM @x.nodes('//t') x(i)
RETURN
END
----Usage
SELECT * FROM SplitString ('1,2,3')
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Logic behind string to integer typecasting..
hi fourm,
i'm siva. i learnt typecasting in java. but i'm still wondering how the string to integer typecasting works, what is the logic behind this casting. somebody please help me out...
Advance thanking
sivapublic static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
public static int parseInt(String s, int radix)
throws NumberFormatException
if (s == null) {
throw new NumberFormatException("null");
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;
if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
multmin = limit / radix;
if (i < max) {
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
} else {
result = -digit;
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
if (result < multmin) {
throw NumberFormatException.forInputString(s);
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
result -= digit;
} else {
throw NumberFormatException.forInputString(s);
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw NumberFormatException.forInputString(s);
} else {
return -result;
}Now where is the missing "logic". -
Convert text box string into integer
i have an html file in which i m using a text box , for entering amount i m using that text box entry at next jsp. i want to convert amount string into integer for further processing. At next jsp i m using:-
String amount= request.getParameter("bal");
int ammount1= Integer.parseInt(ammount);
and in sql query i m using amount1 as:-
ResultSet rs1 = st.executeQuery("update saving set balance = balance - amount1 where saving.account_no = '" + acc +"'");
my problem is i m getting following error:-
server encountered an internal error and
exception:- numberformat exception
please help me as soon as possibleint ammount1= Integer.parseInt(ammount).toString();
good to put try block too..
try
int ammount1 = Integer.parseInt(ammount).toString();
catch(NumberFormatException e)
...} -
Hi Guys,
I am trying to append a String to Integer like this;
String areacode = 020;
Integer phone_no = 21354214;
Integer full = areacode && phone_no;My problem is how to join the two datatypes to a single Integer value. Do anyone know how to go about this?
Bsabre150 wrote:
Skotty wrote:
Without debating the logic of doing such a thing...
Concatenate them as Strings, then convert that String back to an Integer.Your are on the top floor of the Eiffel Tower and a man is trying to climb over the safety netting but having trouble climbing the netting. You ask him why he is doing this and he says he has to get down to the ground as soon as possible but he has an irrational fear of lifts. Do you help him climb the safety netting or do you advise him that this is not a good idea and try to stop him?I get him to use my camera to take my picture. -
Converting String to unicode encoded string
Hi,
I would like to convert non-ascii characters in a String or the whole string to unicode encoded character.
For example:
If i have some japanese character, I would like it to be converted to /uxxxx
How can i do this? I don't want the exact character, as I am able to get that using getBytes("encoding format"). All i want is code point representation of the non ascii unicode characters.
Any help to do this will be appreciated.
Thanks in advance.I tried to do what that but I am not sure whether that is right or not.
String inputStr = "some non ascii string";
char[] charArray = inputStr.toCharArray();
int code;
StringBuffer sb = new StringBuffer();
for(int i = 0; i < charArray.length; i++)
code = (int) charArray;
String hexString = Integer.toHexString( code );
sb.append(hexString);
System.out.println("Code point is "+sb.toString());
My above code does not work as expected. Could you please tell me where i am goofing?
Thanks! -
Converting String type to inte type
Can any one tell me how I can convert an array of Strings into an array of integers??
it's simple ..... it's like this...
// some code goes here....
String num[]={"23", "342", "21", "1"};
int n[]= new int[num.length];
for(int i=0; i<num.length; i++)
n=Integer.parseInt(num[i]); // << -- convert string to int then copied it to int[]
// rest of your code.... -
I cannot convert this string to integer.
int tempI = Integer.parseInt("fdcedfbd", 16);
it returns a numberFormatException
but if I do this then there will be no problem.
int tempI = 0xfdcedfbd
Can anybody help me with this? Thank you.It sounds like the real problem here is that someone is giving you an 8-byte unsigned value represented as a 16-character hexadecimal string, and they want you to convert that into the actual 8 bytes. Are they going to do bit manipulation on it or something?
If you successfully convert it into a long and they then try to do math with it, they'll run into the sign/overflow problems everyone else has been talking about. If they just want to look at the individual bits then it would make sense to do the conversion into a long.
You could do something like this:
private static final String highOrderDigits = "89abcdef";
public long hexToLong(String hex) {
// Only process exactly 16-digit strings.
if (hex.length() != 16) {
throw new IllegalArgumentException("Expect 16-digit hex value");
boolean overflow = false;
// Check for most significant digit > 7, which would
// cause problem for parseLong.
int highOrderIndex = highOrderDigits.indexOf(hex.charAt(0));
if (highOrderIndex > -1) {
// Clear most-significant bit and set overflow flag.
overflow = true;
hex = "" + highOrderIndex + hex.substring(1);
long result = Long.parseLong(hex, 16);
if (overflow) {
// Manually set most significant bit in result.
result |= 0x8000000000000000L;
return result;
}I more or less tested this and it looks to work. -
Is there any native method for converting String value to Hungarian notat..
Hello. there.
This might be very simple question. but I'm just curious about this.
I am wondering if Java API offer the any native method for converting uppercased string value to lowercase which obey the Hungarian notation.
What I'm going to do is using Reflection for excuting RFC function on SAP. I was found it is very similar to JDBC Programming.
Please refer to blow codes.
//mTable
JCoTable mTable = function.getTableParameterList().getTable(rtnTblNm);
for (int i = 0; i < mTable.getNumRows(); i++) {
mTable.setRow(i);
HashMap tmpData = new HashMap ();
for (int j=0; j < mTable.getNumColumns(); j++) {
// I want to set key String [userNo] instead of [USER_NO] here.
tmpData.put(mTable.getMetaData().getName(j).toLowerCase(), mTable.getString(j));
result.add(tmpData);
} Basically, The idea was from ibatis framework [com.ibatis.common.beans.classInfo] dropcase();
Any idea would be very helpful for me. Thank you.
Edited by: hosung.seo on Aug 30, 2009 10:42 PM
Edited by: hosung.seo on Aug 30, 2009 10:50 PMejp wrote:
Hungarian notation is a representation of logical/arithmetic expressions in postfix form. Not what you're talking about.
So your title is very confusing to the people here who know what it means, which is probably all of them, because people read threads based on their title.From now on, I will pay more attention when I post an question.
If the titile as " +Is there any native method for converting String value to camelcase?"+ would be easier to what i'm pointing at.
As I mentioned in above sorce code, converting [USER_NO] to [userNo] isn't relevant Hungarian notation. yes, it was ambiguous. Agree! :)
But some answer wasn't fit to converting case or recognizing "underscore" delimiter. I was expecting toCamelCase() such as blew. Thanks.
public static String toCamelCase(String name) {
String lowerName = name.toLowerCase();
String[] pieces = lowerName.split("_");
if (pieces.length == 1) {
return lowerName;
StringBuffer result = new StringBuffer(pieces[0]);
for (int i = 1; i < pieces.length; i++) {
result.append(Character.toUpperCase(pieces.charAt(0)));
result.append(pieces[i].substring(1));
return result.toString(); -
Easier Way to convert Hex to Integer
This problem is mainly to do with a hex string to integer conversion. The device, connected via serial connection outputs hex in the format 0A00, when looking at it in hex. The first two digits are the data, the last two are attached to seperate data points. what I'm trying to do is to raster the last 2 digits off so that 2A00 becomes 2A and then convert the 2A into integer format (42). I have come up with a method to do this, but it is very messy and occasionally results in data loss. I have attached my vi (8.2). The large integer being subtracted is a constant that continues to come up for reasons I am not aware of.
another issue which I am coding through is the fact that sometimes a byte slips by, making 2A00 become 00BB or something of that format. Is there a way to scan the string, determine whether the first two digits or the last two digits are the valid ones and then seperate the valid string? In this code, it would be necessary to allow for the value 0000 to read 0.
If there is confusion, here is some examples of incoming data and desired output
0100 - 1
0A00 - 10
0005 -5
000B - 11
etc.
Solved!
Go to Solution.
Attachments:
geiger read.vi 28 KBSince you are reading 2 bytes, it looks like you should be dealing with a 16 bit number. Typecast to U16 rather than I32 like you are doing now. And all of that string manipulation make it look like you are getting a string of ASCII formatted characters like "0" "A" "1" "B" rather than a 2 byte string of ASCII characters 0A and 1B. Then you can split the U16 number and take the higher order byte.
I can't explain why you would be having a byte slip by unless it has something to do with all that string manipulation you are trying to do. But if it still happens, and you know one byte for the other is always zero. Just take the high order byte and add it to the low order byte. Since one is zero, it will have no effect on the other byte.
Message Edited by Ravens Fan on 07-07-2009 01:54 PM
Attachments:
geiger%20read[1]_BD.png 3 KB -
Not able to convert string attribute to number and date please help me out
not able to convert string attribute to number and date attribute. While using string to date conversion it shows result as failure.As I am reading from a text file. please help me out
Hi,
You need to provide an example value that's failing and the date formats in the reference data you're using. It's more than likely you don't have the correct format in your ref data.
regards,
Nick
Maybe you are looking for
-
2 ranges of sales order date to be displayed under one coloum.
Hi ALL, I need the o/p of the two select-options to be displayed in a single column?? EX : sodat1 1.10.2006 TO 20.10.2007 sodat2 1.12.2008 TO 20.10.2009 I need these dates to be displayed in a sin
-
To Whom it may Concern, I am attempting to add two columns Comm_id and Ben_id to a table in SQL Developer (Oracle). Here is the syntax I am using: ALTER TABLE ACCTMANAGER ADD (Comm_id NUMBER(10)), Ben_id VARCHAR(2); The spool file I'm getting as a re
-
Dataguard Error in logs Unable to post result to client, status = ORA-16531
Hi, we are getting the following error message in the data guard logs: =================================================================== DG 2012-01-23-17:39:44 0 2 0 DMON: Failed to publish large message. Error is 0xffffff81 DG 2012-01-23-17:39:44
-
MobileMe Gallery Webpage Viewed on iPad
Made a MobileMe Gallery webpage and when viewed on a PC or Mac there are various buttons at the top of the page, one of which is Download and at the bottom there are also buttons to start a Slideshow etc. Anyone know why these buttons are not there w
-
Hello Friends, The extractor 2LIS_03_UM in RSA7 is RED and when I try to check the entriesin the delta queue, it errors with the message" There are still no parameters available for the delta transfer". How to correct this error. Thanks Simmi