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).

4
  • Possible duplicate stackoverflow.com/questions/5387208/… Commented Nov 26, 2017 at 11:10
  • Using the solution in that question gives me ['54776f204f6e65204e696e652054776f'] Commented Nov 26, 2017 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. Commented Nov 26, 2017 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. Commented Nov 26, 2017 at 21:35

2 Answers 2

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']]
Sign up to request clarification or add additional context in comments.

1 Comment

Voted up as I think this is the most readable and thus maintainable solution.
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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.