简体   繁体   English

如何在PHP中编码字节数组

[英]How to encode array of bytes in PHP

I am trying to encode an array of bytes in PHP, and decode it to byte array (ACE_Byte* = unsigned char*) using C++ with ACE, so far without success. 我正在尝试在PHP中对字节数组进行编码,然后使用带有ACE的C ++将其解码为字节数组(ACE_Byte * = unsigned char *),到目前为止没有成功。 My guess is that the encoding in PHP doesn't work well, since the decode is plain and simple: I tried the encoding below without success. 我的猜测是,PHP中的编码无法正常工作,因为解码既简单又简单:我尝试了以下编码,但均未成功。 Can anybody help me find a good way to encode? 有人可以帮我找到编码的好方法吗?

/// Encoding in PHP
public function EncodeArray(){
        $myArray = array();
        $myArray[0] = 'A';
        $myArray[1] = 'B';
        $myArray[2] = 'C';
        $myArray[3] = 15;           
        $myArray[4] = 250;  

        //First try
        $serialized = serialize($myArray); 
        $mySerializedString = base64_encode($serialized);
        return $mySerializedString;

        //Second try
        $imploded = implode($myArray);
        $myImplodedString = base64_encode($imploded);
        return $myImplodedString;

        //Third try         
        $packed = pack('C*',$myArray);
        $myPackedString = base64_encode ($packed);
        return $myPackedString;
}

///Decoding in C++ using ACE library    
bool DecodeString(std::string& myString)        
{
    size_t uiLength;
    const ACE_Byte* p_myArray =  ACE_Base64::decode((const ACE_Byte*)myString.c_str(),&uiLength);
    if(p_myArray == NULL)
    {
        return false;
    }
    return true;
}

I have found the solution. 我找到了解决方案。 It was, as @VolkerK mentioned (Thanks for that!) - using string instead of a char. 就像@VolkerK提到的(谢谢!)-使用字符串而不是char。 In addition, the use of the pack should have been different: 此外,包装的用途应有所不同:

/// Encoding in PHP
public function EncodeArray(){
    $myArray = array();
    $myArray[0] = ord('A'); //or a number, like: 0x40;
    $myArray[1] = ord('B');
    $myArray[2] = ord('C');
    $myArray[3] = 15;           
    $myArray[4] = 250;  
    $Length = 5;            

    for($i = 0; $i < $Length; $i++)
    {
        //concat the string
        $myPackedString = $myPackedString . pack('C',$myArray[$i]); 
    }

    $myPackedString = base64_encode ($myPackedString);
    return $myPackedString;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM