How to convert 4 hex bytes into a single integer

22 ビュー (過去 30 日間)
Elliot
Elliot 2013 年 1 月 31 日
I'm trying to convert the 4 byte sequence:
in hex:
[3E 29 C3 39]
in dec:
62 41 195 57
Manually converting this into an unsigned long (4-byte) integer (uint32):
A(1)*(256^3) + A(2)*(256^2) + A(3)*256 + A(4)
ans =
1042924345
Which is the proper value. However, when I use typecast, I get the wrong value:
>>typecast(A,'int32')
ans =
0 1078919168 0 1078231040 0 1080582144 0 1078755328
>>typecast(int8(A),'int32')
ans =
964634942
Am I doing something wrong here? I've using all variations of signed vs. unsigned integer types (both uint8/int8 and uint32/int32) and none of them give the right answer.
  1 件のコメント
James Tursa
James Tursa 2013 年 1 月 31 日
編集済み: James Tursa 2013 年 1 月 31 日
FYI, turning a value of 195 into an int8 will clip it at the upper end and produce a 127 value (different bit pattern than what you were expecting). You should in general be using unsigned integer classes for this, since MATLAB does not do modulo style conversions ... it clips instead.

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

採用された回答

James Tursa
James Tursa 2013 年 1 月 31 日
編集済み: James Tursa 2013 年 1 月 31 日
Depending on the machine you are on, you may need to use the swapbytes function as well. E.g., try:
swapbytes(typecast(uint8(A),'uint32'))
  1 件のコメント
Elliot
Elliot 2013 年 1 月 31 日
This was apparently the issue. Thank you.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by