2012-10-26 178 views
1

我已經搜索了Stackoverflow並且不幸沒有出現。我正在使用FIX協議,我需要生成一個Modulo 256校驗和,如http://fixwiki.fixprotocol.org/fixwiki/CheckSum所述。在PHP中計算Modulo 256校驗和

$count = strlen($message); 
$count = $count % 256; 
$checksum = 256 - $count; 

if(strlen($checksum) == 1) { 
    $checksum = '00' . $checksum; 
} 

if(strlen($checksum) == 2) { 
    $checksum = '0' . $checksum;  
} 

使用的FIX字符串:

8 = FIX.4.2 | 9 = 42 | 35 = 0 | 49 = A | 56 = B | 34 = 12 | 52 = 20100304-07:59 :30

它應該返回:

8 = FIX.4.2 | 9 = 42 | 35 = 0 | 49 = A | 56 = B | 34 = 12 | 52 = 20100304-07:59:30 | 10 = 185 |

但是我的腳本返回:

8 = FIX.4.2 | 9 = 42 | 35 = 0 | 49 = A | 56 = B | 34 = 12 | 52 = 20100304-07:59:30 | 10 = 199 |

如果有人能指引我走向正確的方向,我將不勝感激!

+0

檢查這個帖子http://stackoverflow.com/questions/2959788/good-tutorial-about-the-fix-protocol – FabianoLothor

+0

我確實有看看那個線程,但我看不到任何特定的計算我需要以上。 – Ashley

+0

$ count的值是多少? – FabianoLothor

回答

3

根據http://fixwiki.fixprotocol.org/fixwiki/CheckSum校驗不是消息模的只是長度256
這是每個字符的總和(如ASCII值)模256

<?php 
define('SOH', chr(0x01)); 

$message = '8=FIX.4.2|9=42|35=0|49=A|56=B|34=12|52=20100304-07:59:30|'; 
$message = str_replace('|', SOH, $message); 
echo $message, GenerateCheckSum($message); 

function GenerateCheckSum($message) { 
    $sum = array_sum(
     array_map(
      'ord', 
      str_split($message, 1) 
     ) 
    ); 
    $sum %= 256; 
    return sprintf('10=%03d%s', $sum, SOH); 
} 

打印

8=FIX.4.2 9=42 35=0 49=A 56=B 34=12 52=20100304-07:59:30 10=185 

或接近文檔中的示例功能

<?php 
define('SOH', chr(0x01)); 

$message = '8=FIX.4.2|9=42|35=0|49=A|56=B|34=12|52=20100304-07:59:30|'; 
$message = str_replace('|', SOH, $message); 
echo $message, '10=', GenerateCheckSum($message, strlen($message)), SOH; 

function GenerateCheckSum($buf, $bufLen) 
{ 
    for($idx=0, $cks=0; $idx < $bufLen; $cks += ord($buf[ $idx++ ])); 
    return sprintf("%03d", $cks % 256); 
} 
+0

謝謝你!作品一種享受! – Ashley

0

有可能你的字符串有多個字節字符。嘗試mb_strlen

+0

我同時回顯strlen()和mb_strlen(),並且上面的示例都返回56。 – Ashley

+0

這實際上是57,我在複製示例時錯過了一個管道。 – Ashley