Reputation:
In Java i did it like this but how do you do this in Python? Specially the bytesArray[i] = (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;
}
Upvotes: 0
Views: 739
Reputation: 725
Just 'call' the type on the value you want to cast.
>>> stringlist = ['123', '245', '456']
>>> intlist = [int(e) for e in stringlist]
>>> intlist
[123, 245, 456]
This may result in a VauleError exception if the value is not valid for the type you're trying to cast to:
>>> int('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hello'
Upvotes: 1
Reputation: 129914
To answer directly: int(x, 16)
. What you're doing in Python would be a single list comprehension (I'm assuming string looks like af/ce/13/...
)
l = [int(x, 16) for x in string.split('/')]
Upvotes: 3