Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

Convert couple of characters to int

How can I convert couple of characters to int, to keep the question simple let's assume this :

char c1 = '1';
char c2 = '4';
char c3 = '5';

What would be the efficient way to get 145 type int.

Upvotes: 0

Views: 137

Answers (5)

Jason Braucht
Jason Braucht

Reputation: 2368

Strings are ultimately backed by a char[], so you could do the following:

char c1 = '1';
char c2 = '4';
char c3 = '5';
int converted = Integer.parseInt(new String(new char[]{c1, c2, c3}));

There are probably several other perfectly good ways to do this.

Upvotes: 1

Michael Schmeißer
Michael Schmeißer

Reputation: 3417

Here is a more general method to convert a char array to int:

int valueOf(char[] input){
  int result = 0;
  for(char c : input) {
    result *= 10;
    result += Character.digit(c, 10);
  }
  return result;
}

Upvotes: 3

Steve McLeod
Steve McLeod

Reputation: 52478

int myInt = (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0');

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198391

The most correct way to convert a single digit character to an int is Character.digit(char ch, int radix), which can handle values in bases besides 10.

Upvotes: 1

tskuzzy
tskuzzy

Reputation: 36476

int myInt = Integer.parseInt(""+c1+c2+c3);

""+c1 gives you a String containing the char c1, to which you append the characters c2 and c3. Then you use parseInt() to convert it to an integer.

A more straightforward (but less robust) method would be this:

int myInt = 100*(c1-'0') + 10*(c2-'0') + (c3-'0');

c1-'0' gives you the number represented by c1 as opposed to the character code. Then you simply shift things to the correct decimal places and add.

Upvotes: 6

Related Questions