Effacer les filtres
Effacer les filtres

How to convert decimal to binary without adding leading zeros?

1 vue (au cours des 30 derniers jours)
Noor Fatima
Noor Fatima le 18 Déc 2022
Commenté : Image Analyst le 18 Déc 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.

Réponses (2)

Dyuman Joshi
Dyuman Joshi le 18 Déc 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 commentaires
Noor Fatima
Noor Fatima le 18 Déc 2022
@Dyuman Joshi But it takes too much time for large data, Is not there any other way, please
Dyuman Joshi
Dyuman Joshi le 18 Déc 2022
Modifié(e) : Dyuman Joshi le 18 Déc 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?

Connectez-vous pour commenter.


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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by