我正在尝试创建一个使用bitshift
操作的函数,我正在创建的这个函数来自正常工作的C代码。发生的问题是它仅适用于少数几个值。调试这两个函数(MatLab和C)我意识到在bitshift
操作中是问题,在C中值为27
而MatLab得到378
。下面是两个函数,C代码用printf()
调用来查看每行之后的值,在MatLab中我使用了自己的调试。
C:
int main()
{
unsigned char value = 189;
printf("\nValue: %d",value);
signed char temp,temp2;
// cast to signed value
temp = (signed char) value;
// if MSB is 1, then this will signed extend and fill the temp variable with 1's
printf("\nTemp signed:%d",temp);
temp = temp >> 7;
// AND with the reduction variable
printf("\nTemp << 7: %d",temp);
temp = temp & 0x1b;
printf("\nTemp and: %d",temp);
temp2 = value<<1;
printf("\nValue << 1: %d");
// finally shift and reduce the value
printf("\nGalois Value: %d", (temp2^temp));
}
MatLab的:
value = uint16(189);
hex = uint16(hex2dec('1B'));
temp = typecast(value, 'int8');
temp = bitshift(temp,-7);
temp = bitand(typecast(temp,'uint16'),hex);
temp2 = bitshift(value,1);
galois_value = bitxor(temp2,uint16(temp));
disp(galois_value);
我用来测试它的一些输入值:
48,105,189,112,182,97,96,78,98,236,51,5,5,183,248,231,149,145,248,170,86,143,134,31,186,94,226,64,181,207,64,51,15,119,113,130
使用此值,预期的输出是(来自C代码):
96,210,97,224,119,194,192,156,196,195,102,10,10,117,235,213,49,57,235,79,172,5,23,62,111,188,223,128,113,133,128,102,30,238,226,31
但是我从matlab代码中得到了这个值:
96,210,353,224,375,194,192,156,196,451,102,10,10,373,491,469,305,313,491,335,172,261,279,62,367,188,479,128,369,389,128,102,30,238,226,287
基本上出现了什么问题:在我的bitshift(value,1)
操作中temp2
应该等于27
(十六进制值),但这个值得到378
。调试C代码我理解temp2
变量在27
operaton等于temp >> 7
的时候应该等于-1
,当temp >> 7
操作的结果时等于0
temp2
的值也应该是0
,对于这种情况(temp >> 7
操作等于0)MatLab中的函数正在工作,但是当它相等时{ {1}} -1
获取错误的值。
有人知道如何解决这个问题吗?
答案 0 :(得分:2)
这个Matlab代码与我接下来提供的C代码具有完全相同的结果。
input_array = [48,105,189,112,182,97,96,78,98,236,51,5,5];
for (i = 1:length(input_array))
value = uint8(input_array(i));
temp = typecast(value, 'int8');
temp = bitshift(temp,-7);
hex = int8(hex2dec('1B'));
temp = bitand(temp,hex);
temp2 = typecast(bitshift(value,1),'int8');
galois_value = typecast(bitxor(temp2,temp),'uint8');
disp(galois_value);
end
#include <stdio.h>
unsigned char input_array[] = { 48, 105, 189, 112, 182, 97, 96, 78, 98, 236, 51, 5, 5 };
int main()
{
for (int i = 0; i < 13; ++i)
{
unsigned char value = input_array[i];
//printf("\nValue: %d", value);
signed char temp, temp2;
// cast to signed value
temp = (signed char)value;
// if MSB is 1, then this will signed extend and fill the temp variable with 1's
//printf("\nTemp signed:%d", temp);
temp = temp >> 7;
// AND with the reduction variable
//printf("\nTemp << 7: %d", temp);
temp = temp & 0x1b;
//printf("\nTemp and: %d", temp);
temp2 = value << 1;
//printf("\nValue << 1: %d");
// finally shift and reduce the value
printf("\nGalois Value: %d", unsigned char(temp2^temp));
//printf("\n done");
}
printf("\n done");
}
两种情况下的输出是: 96 210 97 224 119 194 192 156 196 195 102 10 10