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

27 次查看(过去 30 天)
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

采纳的回答

dpb
dpb 2018-8-26
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 个评论
dpb
dpb 2018-8-27
编辑:dpb 2018-8-29
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by