How to divide 8 bit binary into two 4 bit?

14 ビュー (過去 30 日間)
sami ullah
sami ullah 2020 年 10 月 24 日
コメント済み: Walter Roberson 2023 年 4 月 20 日
For example A=11001111,
i want to break it as A1=1100 and A2=1111.
How it can be done in matlab?

採用された回答

madhan ravi
madhan ravi 2020 年 10 月 24 日
A = '11001111'
A = mat2cell(A, 1, [4, 4]);
celldisp(A)
  3 件のコメント
sami ullah
sami ullah 2020 年 10 月 25 日
If i change A to like this
A = '1100'
A = mat2cell(A, 1, [4, 4]);
celldisp(A)
it gives the following error
Error using mat2cell (line 97)
Input arguments, D1 through D2, must sum to each dimension of the input matrix size, [1 4].'
I need output like this
A1=0000
A2=1100
sami ullah
sami ullah 2020 年 10 月 25 日
I did it as:
N=12;
A=dec2bin(A,8)
A=mat2cell(A, 1, [4, 4]);
celldisp(A)
And it is done
Thanks

サインインしてコメントする。

その他の回答 (1 件)

Xavier
Xavier 2023 年 4 月 20 日
編集済み: Xavier 2023 年 4 月 20 日
I think it would be more efficient in a bit-wise operation performing the modulus and the division.
Start with an 8-bit binary number. For example, let's use the binary number 11011010. To split this number into two 4-bit groups, we need to find the remainder of the number when divided by 16 (which is 2^4, the number of bits in a 4-bit group).
To do this, we can use the modulus operator (%), which gives us the remainder after division.
So, 11011010 % 16 = 10.
The remainder we obtained in step 2 represents the least significant 4 bits of the original number. To get the most significant 4 bits, we need to divide the original number by 16 and discard the remainder. We can use integer division to do this.
So, 11011010 / 16 = 1101.
We now have two 4-bit groups: 1101 and 1010. The first group (1101) represents the most significant 4 bits of the original number, and the second group (1010) represents the least significant 4 bits.
Therefore, the original 8-bit binary number 11011010 can be split into two 4-bit groups: 1101 and 1010.
  1 件のコメント
Walter Roberson
Walter Roberson 2023 年 4 月 20 日
Note that integer division for this purpose is idivide
If you were to use a uint8() / 16 then the output uint8 would be rounded.
There are other approaches. For example,
A = randi([0 255], 5, 1, 'uint8')
A = 5×1
89 241 191 120 243
top_bits = bitand(A, 240) / 16
top_bits = 5×1
5 15 11 7 15
bottom_bits = bitand(A, 15)
bottom_bits = 5×1
9 1 15 8 3
%cross check
dec2hex(A, 2) == [dec2hex(top_bits,1), dec2hex(bottom_bits,1)]
ans = 5×2 logical array
1 1 1 1 1 1 1 1 1 1

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by