フィルターのクリア

How to convert decimal to binary without adding leading zeros?

1 回表示 (過去 30 日間)
Noor Fatima
Noor Fatima 2022 年 12 月 18 日
コメント済み: Image Analyst 2022 年 12 月 18 日
A =[170;149;219;21;0;62;255];
B = dec2bin(A)
'10101010'
'10010101'
'11011011'
'00010101'
'00000000'
'00111110'
'11111111'
I want to remove leading zeros
i.e., the out put should be
10101010
10010101
11011011
10101
0
111110
11111111
I have tried the following
A =[170;149;219;21;0;62;255]
B = dec2bin(A)
B = regexprep( B, '^[0]+', ' ')
But it give the following error
Error using regexprep
The 'STRING' input must be either a char row vector, a cell array of char row vectors, or a
string array.

回答 (2 件)

Dyuman Joshi
Dyuman Joshi 2022 年 12 月 18 日
You will not be able to do that in a char array, due to inconsistent dimensions.
You can, however, obtain the desired result in form of a string array or cell array
A =[170;149;219;21;0;62;255];
y=arrayfun(@(x) string(dec2bin(x)),A)
y = 7×1 string array
"10101010" "10010101" "11011011" "10101" "0" "111110" "11111111"
z=arrayfun(@(x) dec2bin(x), A, 'uni', 0)
z = 7×1 cell array
{'10101010'} {'10010101'} {'11011011'} {'10101' } {'0' } {'111110' } {'11111111'}
  3 件のコメント
Noor Fatima
Noor Fatima 2022 年 12 月 18 日
@Dyuman Joshi But it takes too much time for large data, Is not there any other way, please
Dyuman Joshi
Dyuman Joshi 2022 年 12 月 18 日
編集済み: Dyuman Joshi 2022 年 12 月 18 日
Try this, it should be faster than arrayfun
%preallocation
y=cell(size(A));
for i=1:size(A,1)
y{i}=dec2bin(A(i));
end
Also, how large is your data?

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


Walter Roberson
Walter Roberson 2022 年 12 月 18 日
A =[170;149;219;21;0;62;255]
B = cellstr(dec2bin(A));
B = regexprep( B, '^0+', '', 'once')
But I wonder if you are looking for character representation or if you are looking for for decimal encoded binary, such as 101 decimal output for decimal 5?
  4 件のコメント
Noor Fatima
Noor Fatima 2022 年 12 月 18 日
@Walter Roberson Your code works well, but incase of zero I need zero, is it possible?
Image Analyst
Image Analyst 2022 年 12 月 18 日
@Noor Fatima as I'm sure you know, a simple for loop will do it:
A =[170;149;219;21;0;62;255];
B = cellstr(dec2bin(A));
B = regexprep( B, '^0+', '', 'once');
for k = 1 : numel(B)
if isempty(B{k})
B{k} = '0';
end
end
B
B = 7×1 cell array
{'10101010'} {'10010101'} {'11011011'} {'10101' } {'0' } {'111110' } {'11111111'}
but maybe you're hoping for something more compact and cryptic.

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by