Bitwise OR and Bitwise shift

6 ビュー (過去 30 日間)
Das Siddharth
Das Siddharth 2021 年 4 月 26 日
コメント済み: Walter Roberson 2021 年 4 月 26 日
I am trying to write a matlab code pretty much like the following C code :
uint8_t data[6];
uint32_t tdata = data[3] & 0x0F;
tdata <<= 8;
tdata |= data[4];
tdata <<= 8;
tdata |= data[5];
temperature = ((float)tdata * 200 / 0x100000) - 50;
I recently started using MATLAB and how I translated the above code is something like this :
uint32(tdata) = data(3) & 0x0F;
uint32(tdata) = bitshift(tdata,8);
uint32(tdata) = bitor(tdata,data(4));
uint32(tdata) = bitshift(tdata,8);
uint32(tdata) = bitor(tdata,data(5));
temperature = (tdata*200/1048576)-50;
It's throwing a lot of errors and I am quite stuck. Please help me out here. Thank you in advance.
  2 件のコメント
Matt J
Matt J 2021 年 4 月 26 日
編集済み: Matt J 2021 年 4 月 26 日
We cannot run your code without being given "data" and "tdata".
Das Siddharth
Das Siddharth 2021 年 4 月 26 日
Actually, these are the datas I am getting from a sensor. It's in real-time. That's why I didn't post it here. I just wanted to know if we translate that code what's the correct way.

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

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 4 月 26 日
編集済み: Walter Roberson 2021 年 4 月 26 日
temperature = double(bitand(data(4), 0x0f) * 65536 + data(5) * 256 + data(6)) * 200 / double(0x100000) - 50;
  2 件のコメント
Das Siddharth
Das Siddharth 2021 年 4 月 26 日
Wow ! Can we do this ? I mean without any bitshifts ? These are datas from an AHT20 temperature sensor btw.
Walter Roberson
Walter Roberson 2021 年 4 月 26 日
Use. You are using non-overlapping fields. Shift by multiplying, and add the components.
There are other ways of doing the calculation, but you run into hassles about the fact that MATLAB is little-endian on all current platforms, so doing bit operations is not the same as doing mathematical operations.
For example,
typecast( [data(6), data(5), bitand(data(4), 0x0f), uint8(0)], 'uint32') %slam together little-endian style

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by