こんにちは、文字列を int 配列に変換する方法です。いくつかの暗号化に必要です。32ビット値に変換された単なる文字列。
私はそれを試しましたが、うまくいきませんでした。おそらく、文字列を BigInteger に変換してから、これを生の文字列に変換してから int 配列に変換できますか?
String s = "Alice";
int[] tab = s.getBytes();
こんにちは、文字列を int 配列に変換する方法です。いくつかの暗号化に必要です。32ビット値に変換された単なる文字列。
私はそれを試しましたが、うまくいきませんでした。おそらく、文字列を BigInteger に変換してから、これを生の文字列に変換してから int 配列に変換できますか?
String s = "Alice";
int[] tab = s.getBytes();
このようなものがうまくいくと思います: ここで見つけました: 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 を int 配列に変換する場合は、Joel の String encoding に関する記事を読んでください。あなたが考えるほど明白ではありません。
試す :
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);
}
エンコーディングなしで文字列をバイトに変換することはできません。
この既存の方法を使用する必要があります。
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];
}
バイトに変更: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)
キャストは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];
プリミティブ変換の拡大規則は、プリミティブ型の配列には適用されません。たとえば、Java でバイトを整数に割り当てることは有効です。
byte b = 10;
int i = b; //b is automatically promoted (widened) to int
ただし、プリミティブ配列は同じようには動作しないため、 の配列が の配列byte[]
に自動的にプロモートされると想定することはできません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.
}
私にとっては、これが最も簡単なアプローチです。