2012-09-18 31 views
2

我試圖將一些PHP轉換爲C#,但按位函數給了我不同的結果。按位移 - 在C#中獲取不同於PHP的結果

PHP將返回248

protected function readInt8() 
{ 
    $ret = 0; 
    if (strlen($this->_input) >= 1) 
    { 
     $sbstr = substr($this->_input, 0, 1); 
     $ret = ord($sbstr); 
     $this->_input = substr($this->_input, 1); 
    } 
    return $ret; 
} 

C#將返回63

private int ReadInt8() 
{ 
    int ret = 0; 
    if (input.Length >= 1) 
    { 
     string substr = input.Substring(0, 1); 
     ASCIIEncoding ascii = new ASCIIEncoding(); 
     byte[] buffer = ascii.GetBytes(substr); 
     ret = buffer[0]; // 63 

     this.input = this.input.Substring(1); 
    } 

    return ret; 
} 

或將返回14337

private int ReadInt8() 
{ 
    int ret = 0; 

    if (input.Length >= 1) 
    { 
     string substr = input.Substring(0, 1); 

     ret = (int)(substr[0]); // 14337 
     this.input = this.input.Substring(1); 
    } 

    return ret; 
} 

other question這裏有更大的價值工作,但它不」 t與較小的值一起工作。我想知道問題是什麼。

對不起。昨天有點晚了。

bytes from the server

下面= 「Ԁϸ㠁鋰Ǹϸ붻ªȁ」 功能轉換的輸入;

public string GetString(byte[] bytes) 
{ 
    char[] chars = new char[bytes.Length/sizeof(char)]; 
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); 
    return new string(chars); 
} 

關於這個轉變。我認爲這可能需要一個轉變,因爲ReadInt16()需要它。

private int ReadInt16() 
{ 
    int ret = 0; 
    if (input.Length >= 2) 
    { 
     ret = ((int)(this.input.Substring(0, 1)[0]) & 0xffff) >> 8; 
     ret |= ((int)(this.input.Substring(1, 1)[0]) & 0x0000) >> 0; 
     this.input = input.Substring(2); 
    } 
    return ret; 
} 

我應該說。我可能誤解了在PHP中使用該函數。

+0

這將有助於如果你告訴我們的輸入開始... –

+3

我沒有看到你的代碼中的任何按位移。 – CodesInChaos

+4

63是'?'的ASCII碼,這意味着沒有有效的ASCII字符爲你想要的。請記住只有值<128是ASCII。 – CodesInChaos

回答

2

不要將字符串視爲等同於字節數組。字符編碼會干擾和破壞數據(如果它實際上不是文本)。如果您必須以文本方式傳輸原始數據,則必須對其進行適當的編碼/解碼,例如使用base64編碼。