您好如何将 String 转换为 int 数组。我需要它来进行一些加密。只是一个转换为 32 位值的字符串。
我试过了,但没有用。也许将 String 转换为 BigInteger 然后将其转换为原始 String 然后转换为 int 数组会起作用吗?
String s = "Alice";
int[] tab = s.getBytes();
您好如何将 String 转换为 int 数组。我需要它来进行一些加密。只是一个转换为 32 位值的字符串。
我试过了,但没有用。也许将 String 转换为 BigInteger 然后将其转换为原始 String 然后转换为 int 数组会起作用吗?
String s = "Alice";
int[] tab = s.getBytes();
如果您要将 String 转换为 int 数组,请阅读Joel 关于 String encoding 的文章,它并不像您想象的那么明显。
我认为这样的事情对你有用:在这里找到它:http: //pro-programmers.blogspot.com/2011/05/java-byte-array-into-int-array.html
public int[] toIntArray(byte[] barr) { 
        //Pad the size to multiple of 4 
        int size = (barr.length / 4) + ((barr.length % 4 == 0) ? 0 : 1);       
        ByteBuffer bb = ByteBuffer.allocate(size *4); 
        bb.put(barr); 
        //Java uses Big Endian. Network program uses Little Endian. 
        bb.order(ByteOrder.BIG_ENDIAN); 
        bb.rewind(); 
        IntBuffer ib =  bb.asIntBuffer();         
        int [] result = new int [size]; 
        ib.get(result); 
        return result; 
}
调用它:
String s = "Alice";     
int[] tab = toIntArray(s.getBytes()); 
尝试 :
String s = "1234";
int[] intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
    intArray[i] = Character.digit(s.charAt(i), 10);
}
更改为字节:byte[] tab = s.getBytes();
final String s = "54321";
final byte[] b = s.getBytes();
for (final byte element : b) {
    System.out.print(element+" ");
}
输出 :
53 52 51 50 49
编辑
(int)cast 被 Eclipse 删除System.out.print((int) element+" ");
除非你想投int myInteger = (int) tab[n],否则你必须复制byte[]一个新的  int[]
        String s = "Alice";
        byte[] derp = s.getBytes();
        int[] tab = new int[derp.length];
        for (int i=0; i< derp.length; i++)
            tab[i] = (int)derp[i];
没有编码就不能将字符串转换为字节。
您需要使用这个已经存在的方法:
public static final byte[] getBytesUtf8( String string )
  {
      if ( string == null )
      {
          return new byte[0];
      }
      try
      {
          return string.getBytes( "UTF-8" );
      }
      catch ( UnsupportedEncodingException uee )
      {
          return new byte[]
              {};
      }
  }
}
然后将其更改为 int 数组,如下所示:  byte[] bAlice
int[] iAlice = new int[bAlice.length];
for (int index = 0; index < bAlice.length; ++index) {
     iAlice [index] = (int)bAlice[index];
}
扩大原始转换的规则不适用于原始类型的数组。例如,在 Java 中将一个字节分配给一个整数是有效的:
byte b = 10;
int i = b; //b is automatically promoted (widened) to int
但是,原始数组的行为方式不同,因此,您不能假设数组 ofbyte[]会自动提升为 数组int[]。
但是,您可以手动强制提升字节数组中的每个项目:
String text = "Alice";
byte[] source = text.getBytes();
int[] destiny = new int[source.length];
for(int i = 0; i < source.length; i++){
    destiny[i] = source[i]; //automatically promotes byte to int.
}
对我来说,这将是最简单的方法。