shifting handling in matlab with for loop

9 次查看(过去 30 天)
Hi guys, could anyone please instruct me how I can implement this function that I attached it down in matlab? exactly the if condition and bit left shifting and bitwise and in matlab..
here's my function in c++: ( Im not professionaly in matlab and would be appreciated for any help) ..this function gets two input, one is crcData which it's uint8_t(byte type), second is two bytes type (uint16_t)
thanks alot !
uint16_t calcCRC(uint8_t crcData, uint16_t crcReg)
{
uint8_t i;
for (i = 0; i < 8; i++)
{
if (((crcReg & 0x8000) >> 8) ^ (crcData & 0x80))
{
crcReg = (crcReg << 1) ^ CRC16_POLY;
}
else
{
crcReg = (crcReg << 1);
}
crcData <<= 1;
}
return crcReg;
}
  5 个评论
Jimmy cho
Jimmy cho 2020-8-8
@Walter Roberson thanks for your help!
so how do I write by what you forwarded an equivalent code in matlab to what I've wrote in c++ ? thanks alot.
yes it seems the crc.generator make sense to what I've written in c++ but still not familiar with parametrs of it .. could you please help me how do I write the same crcCalc (that I wrote in c++) in matlab code by using what you forwarded? thanks

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2020-8-8
function crcReg = calcCRC(crcData, crcReg, CRC16_POLY)
for i = 0 : 7
if bitxor( bitshift( bitand(crcReg, 0x8000), -8), ...
bitand( crcData, 0x0080 ) )
crcReg = bitxor( bitshift(crcReg, 1), CRC16_POLY );
else
crcReg = bitshift(crcReg, 1);
end
crcData = bitshft(crcData, 1);
end
Are you sure about the formula? The result is always going to be even, because the shifts are not circular and the final shift will always be a left shift by 1 bit, which is always going to introduce a 0 bit at the end.
  16 个评论
Walter Roberson
Walter Roberson 2020-8-12
sscanf() is like fscanf() except that it does not read from a file and then interpret the characters read according the given format: instead it gets characters from the character vector that is passed to it, and interprets the characters according to the given format.
hex2dec() has a quite different implementation that is designed to work on arrays of data.
sscanf() calls into the fundamental I/O libraries to do its work.
In general, the main advantage of sscanf() is that you can say exactly how many digits at a time you want to read. For example,
sscanf('789ABC', '%3x')
will pull out 3 characters at a time and translate them to decimal, instead of having to do
hex2dec(reshape('789ABC', 3, []).')
... except worse because for the reshape() one you have to pad out to a multiple of 3 first, but the sscanf() version can handle strings that are not full multiples...

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by