Clear Filters
Clear Filters

How to convert decimal to binary without adding leading zeros?

1 view (last 30 days)
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.

Answers (2)

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

Sign in to comment.


Walter Roberson
Walter Roberson on 18 Dec 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 Comments
Image Analyst
Image Analyst on 18 Dec 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.

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!