0

I have a hex string a = 54776f204f6e65204e696e652054776f And I want it in the form of a matrix like this:

s = [[54, 4f, 4e, 20],
     [77, 6e, 69, 54],
     [6f, 65, 6e, 77],
     [20, 20, 65, 6f]]

How do I do it?

For more clarification: I am writing a program for AES encryption and decryption. And this is the 1st part where the plaintext is converted to hexadecimal and then to a state (4x4 matrix).

sciencaholic
  • 123
  • 1
  • 11
  • Possible duplicate https://stackoverflow.com/questions/5387208/convert-a-string-to-an-array – Mr. T Nov 26 '17 at 11:10
  • Using the solution in that question gives me `['54776f204f6e65204e696e652054776f']` – sciencaholic Nov 26 '17 at 11:18
  • You have of course adapt it to split your hex string into chunks of 8 and divide them afterwards in 4x2. But somebody has already been nice enough to do the coding for you. – Mr. T Nov 26 '17 at 11:22
  • I don't agree with the duplicate as this is not about hex conversion in itself, it is mainly about re-arranging the values. But note that within cryptography, it often pays to perform these kind of operations on bytes rather than (character) strings. I good answer would convert to bytes and then rearrange *those*. – Maarten Bodewes Nov 26 '17 at 21:35

2 Answers2

3

This should work:

import numpy as np

a = '54776f204f6e65204e696e652054776f'
n = 2
x = [a[i:i+n] for i in range(0, len(a), n)]

my_matrix = np.array(x).reshape(4, 4).T

print(my_matrix)


[['54' '4f' '4e' '20']
 ['77' '6e' '69' '54']
 ['6f' '65' '6e' '77']
 ['20' '20' '65' '6f']]
1

You can do the following. Chunk the string appropriately and then use the zip(*...) transpositioning pattern:

def group(seq, n):
    return [seq[i:i+n] for i in range(0, len(seq), n)]

>>> a = '54776f204f6e65204e696e652054776f'
>>> list(zip(*group(group(a, 2), 4)))
[('54', '4f', '4e', '20'), 
 ('77', '6e', '69', '54'), 
 ('6f', '65', '6e', '77'), 
 ('20', '20', '65', '6f')]
user2390182
  • 72,016
  • 6
  • 67
  • 89