How can I convert binary vector to a single binary number?

47 views (last 30 days)
Hi
could you please help me? I want to convert a vector which consists binary elements to a single binary number? i want to give 010110 from [0 1 0 1 1 0];(it is necessary for me to keep the first zero) and i want to keep format of number as a binary element because i want to compare the output with other binary numbers

Accepted Answer

dpb
dpb on 26 Aug 2018
The representation as 010110 visually is immaterial; to do that it will have to be character:
b= [0 1 0 1 1 0];
sprintf('%d',b)
ans =
'010110'
For internal comparison to values, just convert to decimal--unfortunately, Matlab doesn't have a scan format string for binary, use
v=uint8(bin2dec(sprintf('%d',b))) % convert to value
v =
22
To compare/find bits...
bitget(v,1:6)
ans =
1×6 uint8 row vector
0 1 1 0 1 0
  8 Comments
dpb
dpb on 27 Aug 2018
Edited: dpb on 29 Aug 2018
You're welcome, glad to (try to) help... :)
Matlab doesn't have the facility; Forth has the system constant BASE which is very useful for such shenanigans; one could write
21 2 BASE ! . DECIMAL
and the value of 21 would be displayed on the terminal in base 2 then the working base returned to base 10. Most define
: BINARY 2 BASE !;
as a "syntactic sugar" word (aka Matlab function) and then above could be shortened to
21 BINARY . DECIMAL
Matlab doesn't have the facility to change working base arbitrarily for the input parser, however, you've got to do it by transforming results.
ADDENDUM
Of course, while the above is very succinct from the user standpoint and an extremely handy facility, it doesn't actually change the underlying fact that the value '21' is still stored as twos-complement integer whether BASE is set at 2 or 10 or 16 or 37 (a value handy to use for encoding simple hash table keys or the like); the same cast operations between internal representation and external display are present, they're just handled "under the hood" by builtin logic within the FORTH engine as part of the core functionality.
Chuck Moore built this in when he invented Forth as he was doing instrumentation and control where bit operations interacting with hardware bit registers was a key component of the application so being able to use a flexible BASE was fundamental to convenience. Matlab, being designed primarily as the MATrix LABoratory didn't have such low-level operations in mind to need a similar facility.

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!