user285594
user285594

Reputation:

How to do Java like type casting (byte) (Integer.parseInt(byteArrayStr[i],16)) in Python?

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

Answers (2)

setrofim
setrofim

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

Cat Plus Plus
Cat Plus Plus

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

Related Questions