Clear Filters
Clear Filters

How can i reshape the code as below

1 view (last 30 days)
Kaavya N
Kaavya N on 2 May 2021
Commented: Kaavya N on 3 May 2021
k=[dec2hex(floor(rand * 2 ^ 96),24),dec2hex(floor(rand * 2 ^ 96),24), dec2hex(floor(rand * 2^ 64),16)];
%k generates random 64 characters
%k = 0924668B8FB8700000000000D96089C6C815880000000000EF1A2E75CDB28000
w=reshape(k,4,[ ]);
%w gives 4x16 char array
% '068700D8C800E2C8'
%'96F000998800FED0'
%'28B0006C100017B0'
%'4B8000065000A520'
how can I group 2 characters as one element and make w a 4x8 matrix like
09 8F ....................
24 B8 .....................
66 .........................
8B ...........................

Accepted Answer

DGM
DGM on 3 May 2021
Try this:
k = '0924668B8FB8700000000000D96089C6C815880000000000EF1A2E75CDB28000'
wo = reshape(k(1:2:end),4,[]);
we = reshape(k(2:2:end),4,[]);
w = reshape([wo; we],4,[])
gives
w =
4×16 char array
'098F00D9C800EFCD'
'24B8006015001AB2'
'6670008988002E80'
'8B0000C600007500'
If you need literal spaces in between each byte, that can be done instead:
wo = reshape(k(1:2:end),4,[]);
we = reshape(k(2:2:end),4,[]);
ws = repmat(' ',[4 8]);
w = reshape([wo; we; ws],4,[])
gives
w =
4×24 char array
'09 8F 00 D9 C8 00 EF CD '
'24 B8 00 60 15 00 1A B2 '
'66 70 00 89 88 00 2E 80 '
'8B 00 00 C6 00 00 75 00 '
Note the method of stacking arrays to implement the striping behavior.

More Answers (1)

Walter Roberson
Walter Roberson on 3 May 2021
Edited: Walter Roberson on 3 May 2021
compose("%02x", reshape(sscanf(k,'%2x'),4,[]))
This will return a 4 x 8 string array, not a char array. If you want a 4 x 8 array, then you need to use a cell array or a string array, or you need to convert to decimal. The reshape(sscanf(k,'%2x'),4,[]) part is doing the conversion to decimal and re-ordering of values.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!