2017-06-05 55 views
1

我正在从Gallois字段乘以2来转录Matlab的C代码,问题是我的matlab代码没有显示与C代码相同的值。显然一切正常,我评论了matlab中的代码来识别代码下方C代码的改编。Galois字段算法从C到Matlab

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代码正常工作,我在C代码中打印%d以显示变量的整数值,因为在代码的开始时强制转换。

有人知道发生了什么

+1

为什么你认为'TEMP = UINT8(HEX2DEC( 'AA'));'等同于'TEMP =(符号字符)值;'? –

+0

你需要看看计算开始发生在什么地方,而不是让我们为你做。 –

+0

在C中的每一行后面加一个'printf',在MATLAB中'disp'。 –

回答

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); 
+0

就像我之前说过的,我没有创建C代码,它来自德克萨斯州的公司,它来自MSP430系列MCU中使用的AES criptography库,我应该假设,当我实现代码的其余部分时,加密将起作用吗?因为原来的德克萨斯功能的输出值是不同的,现在是335,现在是85. – Mutante

+0

@Mutante,对不起。我错过了你正在从C转换到Matlab。我更新了我的帖子。请再看看。 – wyc

+0

'typecast'函数非常有用,我不知道它的存在,谢谢@wyc! – Mutante