How to convert decimal to binary without adding leading zeros?

5 visualizzazioni (ultimi 30 giorni)
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.

Risposte (2)

Dyuman Joshi
Dyuman Joshi il 18 Dic 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 Commenti
Noor Fatima
Noor Fatima il 18 Dic 2022
@Dyuman Joshi But it takes too much time for large data, Is not there any other way, please
Dyuman Joshi
Dyuman Joshi il 18 Dic 2022
Modificato: Dyuman Joshi il 18 Dic 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?

Accedi per commentare.


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

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by