Filter löschen
Filter löschen

How to convert decimal to binary without adding leading zeros?

1 Ansicht (letzte 30 Tage)
Noor Fatima
Noor Fatima am 18 Dez. 2022
Kommentiert: Image Analyst am 18 Dez. 2022
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.

Antworten (2)

Dyuman Joshi
Dyuman Joshi am 18 Dez. 2022
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 Kommentare
Noor Fatima
Noor Fatima am 18 Dez. 2022
@Dyuman Joshi But it takes too much time for large data, Is not there any other way, please
Dyuman Joshi
Dyuman Joshi am 18 Dez. 2022
Bearbeitet: Dyuman Joshi am 18 Dez. 2022
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?

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 18 Dez. 2022
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 Kommentare
Noor Fatima
Noor Fatima am 18 Dez. 2022
@Walter Roberson Your code works well, but incase of zero I need zero, is it possible?
Image Analyst
Image Analyst am 18 Dez. 2022
@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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by