Hex 01A9 to 16-binary?

1 回表示 (過去 30 日間)
WARRIOR24
WARRIOR24 2020 年 12 月 16 日
編集済み: Stephen23 2020 年 12 月 17 日
I am trying to convert this input 01A9 into binary
4bit Hex input
01A9
16bit Binary Output
0000 0001 1010 1001
**no spaces

採用された回答

Walter Roberson
Walter Roberson 2020 年 12 月 16 日
H = '01A9';
dec2bin(sscanf(H, '%4x'),16)
ans = '0000000110101001'
Note that the result will be character.
H can have more than 4 characters, and will be interpreted 4 characters at a time from the beginning . So if H is not an exact multiple of 4 characters, this particular algorithm will not implicitly pad from the begining with 0's -- only the last group will be 0 padded.
dec2bin(sscanf('01A9876', '%4x'),16)
ans = 2x16 char array
'0000000110101001' '0000100001110110'
This was interpretered as 01A9 (0)876.
If you needed to be padded with leading 0s implicitly then that could certainly be programmed.

その他の回答 (2 件)

Stephen23
Stephen23 2020 年 12 月 17 日
編集済み: Stephen23 2020 年 12 月 17 日
No loops, no padding, works correctly for any number of hex digits (not just 16 bits):
H = '01A9';
B = reshape(dec2bin(sscanf(H,'%1x'),4).',1,[])
B = '0000000110101001'

James Tursa
James Tursa 2020 年 12 月 16 日
編集済み: James Tursa 2020 年 12 月 16 日
E.g., if H is not too big:
H = '01A9';
B = dec2bin(hex2dec(H),numel(H)*4)
Otherwise you will need some form of a loop (explicit or hidden in a function call). E.g.,
C = arrayfun(@(h)dec2bin(hex2dec(h),4),H,'uni',false);
B = [C{:}]

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by