0

我正在从 Gallois 字段中乘以 2 为 Matlab 转录 C 代码,问题是我的 matlab 代码显示的值与 C 代码不同。显然一切都很好,我在 matlab 中注释了代码以识别代码下方的 C 代码的改编。

C:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  unsigned char value = 0xaa;
  signed char temp;
  // cast to signed value
  temp = (signed char) value;
  printf("\n%d",temp);
  // if MSB is 1, then this will signed extend and fill the temp variable with 1's
  temp = temp >> 7;
  printf("\n%d",temp);
  // AND with the reduction variable
  temp = temp & 0x1b;
  printf("\n%d",temp);
  // finally shift and reduce the value
  printf("\n%d",((value << 1)^temp));
}

输出:

-86
-1
27
335

MATLAB:

hex = uint8(hex2dec('1B'));                     % define 0x1b
temp = uint8(hex2dec('AA'));                    % temp = (signed char) value;
disp(temp);
value = uint8(hex2dec('AA'));                   % unsigned char value = 0xaa
temp = bitsra(temp,7);                          % temp = temp >> 7;
disp(temp);
temp = bitand(temp,hex);                        % temp = temp and 0x1b  
disp(temp);
galois_value =  bitxor(bitsll(value,1),temp);   % ((value << 1)^temp)
disp(galois_value);                             % printf ("\n%u",...)                    

输出:

 170

    1

    1

   85

C 代码工作正常,我%d在 C 代码中打印以显示变量的整数值,因为在代码的开头进行了强制转换。

有人知道发生了什么

4

1 回答 1

2

试试这个:

hex = uint8(hex2dec('1B')); 

temp = typecast(uint8(hex2dec('AA')), 'int8');
disp(temp);

temp = bitshift(temp,-7); 
disp(temp);

temp = bitand(typecast(temp,'uint8'),hex); 
disp(temp);

galois_value =  bitxor(bitshift(uint16(hex2dec('AA')),1),uint16(temp));   
disp(galois_value);  
于 2017-06-05T19:54:16.470 回答