-4

I need to convert a string to a corresponding int array in java. i wrote the following code but its not working as i expected .

        String temp= "abc1";
        int[] intArray = new int[temp.length()];
        for (int i = 0; i < temp.length(); i++) {
            intArray[i] = Integer.parseInt(temp[i]);
        } 

I have written an rc4 encryption program which take the key and plain text as int arrays. So I need to convert the user specified key to int array before passing it to the encryption function. Is this the correct way of using key in encryption programs?

Javier
  • 12,100
  • 5
  • 46
  • 57
Amar C
  • 374
  • 5
  • 17

4 Answers4

3

Use this to get the ASCII code

intArray[i] = (int)temp.charAt(i);
mprivat
  • 21,582
  • 4
  • 54
  • 64
0

You can convert string to charArray. Travesing charArray you can convert as:

char[] c = inputString.toCharArray()
for(int i=0;i<c.length;i++)
     int n    = Integer.parseInt(c[i]);
Bhavesh Shah
  • 3,299
  • 11
  • 49
  • 73
0

if you are Using Java8 or higher then it might be helpful for you

String temp="abc1";
int[] intArray =temp.chars().map(x->x-'0').toArray();
System.out.println(Arrays.toString(intArray ));

int array would be [49, 50, 51, 1]

-1

I solved this by using byte instead of int. Modified the rc4 to take byte array. converted the string to byte using

    String Nkey = jTextField2.getText();
    jTextField3.setText(Nkey);
    int i;
    byte[] key = Nkey.getBytes();
Amar C
  • 374
  • 5
  • 17