4byte uint8 array to single uint32 value

I have an uint8 array containing 4 elements each representing 1byte.
myArray = [0x32 0x45 0x56 0x81] % just an example
% looks like this: myArray(1)=8bit, myArray(2)=8bit, myArray(3)=8bit, myArray(4)=8bit]
I mainly need to extract all the 32 bits and combine them to one uint32 value:
myValue = 0x32455681
%should look like this 32bit: myArray(1)myArray(2)myArray(3)myArray(4)
The goal is basically to remove the array structure and chain all the 32bits together
I once came from such an uint32 number and used the rearrange and bitget function to crate this array structure, but I somehow don't see how to come back.
As an important requirement, all the used functions must be able to be generate to C code
Any ideas?

 採用された回答

Ameer Hamza
Ameer Hamza 2020 年 12 月 7 日
編集済み: Ameer Hamza 2020 年 12 月 7 日

4 投票

You can use typecast()
myArray = [0x32 0x45 0x56 0x81];
out = swapbytes(typecast(myArray, 'uint32')); % swapbytes is needed on little-endian systems
Result
>> out
out =
uint32
843404929
>> dec2hex(out)
ans =
'32455681'

7 件のコメント

Maximilian Becker
Maximilian Becker 2020 年 12 月 7 日
Thanks alot! I've been trying the exact same thing, but I somehow discarded the solution for no reason.
Way simpler than my latest work around!
Ameer Hamza
Ameer Hamza 2020 年 12 月 7 日
I am glad to be of help! :)
Daryl Lee
Daryl Lee 2022 年 8 月 13 日
I not ewith interest the comment about swapbyes andendian-ness. Is there a portable way to do this, so the same code will run correctly whatever the endian-ness of the host? Kind of like htonl() and ntohl()?
Walter Roberson
Walter Roberson 2022 年 8 月 13 日
No portable function is provided. You can use computer() to probe the host endian.
[C, arch, endian] = computer()
C = 'GLNXA64'
arch = 2.8147e+14
endian = 'L'
MATLAB has only been supported on little-endian hosts for quite a number of years; I believe SGI was the last supported big-endian host.
Daryl Lee
Daryl Lee 2022 年 8 月 13 日
Thanks
Nur Fatin Atirah Mohd Rawi
Nur Fatin Atirah Mohd Rawi 2023 年 5 月 25 日
Do you know how to convert single uint 32 into uint 8?
Steven Lord
Steven Lord 2023 年 5 月 25 日
format longg
x = randi([intmin('uint32') intmax('uint32')], 1)
x =
3159077208
y = typecast(x, 'uint8')
y = 1×8
0 0 0 43 118 137 231 65
format hex
x
x =
41e789762b000000
y
y = 1×8
00 00 00 2b 76 89 e7 41
swapbytes(x)
ans =
0000002b7689e741

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by