フィルターのクリア

Creating a hex array with 4 digit blocks from an array of integers

23 ビュー (過去 30 日間)
Art
Art 2017 年 1 月 21 日
コメント済み: Walter Roberson 2017 年 1 月 22 日
I am using R2013 and need to convert a large decimal array into hex stings.
The decimal numbers can be any positive integer, and I need to convert each number, then display each as a minimum two byte string with preceding zeros (with more bytes shown as the number increases).
e.g. decimal "1" should show up as '0x0001',
decimal "69876" should show up as '0x0001 0x10F4'
I created a rather cumbersome loop that does this perfectly, but with large arrays it takes too long.
I can get part way to a non-loop implementation with this code:
DecArray = [1 2 4 69876];
cellstr(dec2hex(reshape(DecArray,[],1), 4));
ans =
'00001'
'00002'
'00004'
'110F4'
But as you see the outputs
1) always have the same number of digits, and
2) aren't broken into 2 Byte blocks
Is there any way to go from these results to the ones I described earlier without another loop?
  5 件のコメント
Art
Art 2017 年 1 月 22 日
編集済み: Art 2017 年 1 月 22 日
The data can be in 16bit OR 32bit words, so it's just a matter of displaying in the easiest way to read for the data being analyzed. If the dec number is greater than 65535 then it's a 32 bit and should display as such.
Walter Roberson
Walter Roberson 2017 年 1 月 22 日
I dunno. It just seems unlikely to me that the data could vary between 16 and 32 bits on the same plot.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2017 年 1 月 21 日
編集済み: Stephen23 2017 年 1 月 21 日
V = [1,2,4,69876];
L = log(16);
for k = 1:numel(V)
N = 4*(1+fix(log(V(k))/L/4));
S = sprintf('%0*X',N,V(k));
Z = sprintf('0x%c%c%c%c ',S)
end
Prints this in the command window:
Z =
0x0001
Z =
0x0002
Z =
0x0004
Z =
0x0001 0x10F4
Note: does not work for zero: add N = max(4,N)
  1 件のコメント
Art
Art 2017 年 1 月 21 日
Stephen,
This works great and is much simpler than my old loop. If I can't get Guillaume's answer to work then I will accept this. Thanks!

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2017 年 1 月 21 日
DecArray = [1 2 4 69876]';
h = arrayfun(@dec2hex, DecArray, 'UniformOutput', false);
cellfun(@(s) strcat('0x', cellstr(reshape([repmat('0', 1, mod(-numel(c), 4)), c], 4, [])')), d, 'UniformOutput', false)
  3 件のコメント
Walter Roberson
Walter Roberson 2017 年 1 月 22 日
編集済み: Walter Roberson 2017 年 1 月 22 日
d should be h
Art
Art 2017 年 1 月 22 日
I had to substitute h for both d and c, but the output format wasn't quite what I needed.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by