some_other_guy
some_other_guy

Reputation: 3414

Convert an integer to an array of characters : java

What is the best way to convert an integer into a character array?

Input: 1234

Output: {1,2,3,4}

Keeping in mind the vastness of Java language what will be the best and most efficient way of doing it?

Upvotes: 31

Views: 141680

Answers (7)

live-love
live-love

Reputation: 52534

This will convert an int to a 2 char array. If you are trying to get the minimum amount of chars, try this.

//convert int to char array

int valIn = 111112222;

ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.putInt(valIn); 

char [] charArr = new char[4];
charArr[0] = bb1.getChar(0);
charArr[1] = bb1.getChar(2);

//convert char array to int

ByteBuffer bb2 = ByteBuffer.allocate(8);
bb2.putChar(0,charArr[0]);
bb2.putChar(2,charArr[1]);

long valOut = bb2.getInt(0);

Upvotes: 2

Vinit Raj
Vinit Raj

Reputation: 1910

You can convert that integer to string and then convert that string to char arary:-

int i = 1234;
String s = Integer.toString(i);
Char ch[] = s.toCharArray();

/*ch[0]=1,ch[1]=2,ch[2]=3,ch[3]=4*/

Upvotes: 8

CompoterHenius
CompoterHenius

Reputation: 1

Say that you have an array of ints and another method that converts those ints to letters, like for a program changing number grades to letter grades, you would do...

public char[] allGradesToLetters()
   {
      char[] array = new char[grades.length];

      for(int i = 0; i < grades.length; i++)
      {
         array[i] = getLetter(grades[i]);
      }

      return array;
   }

Upvotes: -2

harshad_y
harshad_y

Reputation: 21

I was asked this question in google interview. If asked in interviews use module and division. Here is the answer

List<Integer> digits = new ArrayList<>();
//main logic using devide and module
for (; num != 0; num /= 10)
    digits.add(num % 10);

//declare an array
int[] arr = new int[digits.size()];
//fill in the array
for(int i = 0; i < digits.size(); i++) {
    arr[i] = digits.get(i);
}
//reverse it.
ArrayUtils.reverse(arr);

Upvotes: 1

Bharat Sinha
Bharat Sinha

Reputation: 14383

Try this...

int value = 1234;
char [] chars = String.valueOf(value).toCharArray();

Upvotes: 16

JesperE
JesperE

Reputation: 64454

You could try something like:

String.valueOf(1234).toCharArray();

Upvotes: 53

AlexR
AlexR

Reputation: 115418

int i = 1234;
char[] chars = ("" + i).toCharArray();

Upvotes: 65

Related Questions