How can I convert binary vector to a single binary number?
31 ビュー (過去 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
1 件のコメント
madhan ravi
2018 年 8 月 26 日
Could you show an example of input array and the output you want to get?
採用された回答
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
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 Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!