2011-12-03 7 views
0

Javaではこれが好きでしたが、Pythonでこれをどうやってやっていますか?特別bytesArray[i] = (byte) (Integer.parseInt(byteArrayStr[i],16));PythonでJavaのような型キャスト(byte)(Integer.parseInt(byteArrayStr [i]、16))を行う方法は?

public static byte[] toBytes(String bytes) throws IOException 
    { 
    String byteArrayStr[] = bytes.split("\\/"); 
    byte bytesArray[] = new byte[byteArrayStr.length]; 
    for (int i = 0; i < byteArrayStr.length; ++i) 
    { 
     bytesArray[i] = (byte) (Integer.parseInt(byteArrayStr[i],16)); 
    } 

    return bytesArray; 
    } 

答えて

4

は直接答えるために:int(x, 16)を。あなたはPythonでやっていることは、単一のリスト内包だろう

l = [int(x, 16) for x in string.split('/')] 
2

ただ、「コール」あなたはキャストする値のタイプ(私は仮定していた文字列はaf/ce/13/...のように見えます)。

>>> stringlist = ['123', '245', '456'] 
>>> intlist = [int(e) for e in stringlist] 
>>> intlist 
[123, 245, 456] 

値は、あなたがにキャストしようとしているタイプに対して有効でない場合、これはVauleError例外をもたらすことができる:

>>> int('hello') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: invalid literal for int() with base 10: 'hello' 
関連する問題