簡體   English   中英

構造位掩碼? 按位分組

[英]Constructing bitmask ? bitwise packet

我一直想使用通過TCP連接連接的iOS應用程序來嘗試使用Axon這個項目。 在文檔末尾,對協議的解釋如下

有線協議很簡單,並且非常類似於zeromq,其中是BE 24位無符號整數,表示最大長度約為16mb。 數據字節當前僅用於存儲編解碼器,例如“ json”簡單地為1,然后通過選擇相同的編解碼器,將自動為您解碼在客戶端接收到的JSON消息。

與圖

 octet:     0      1      2      3      <length>
         +------+------+------+------+------------------...
         | meta | <length>           | data ...
         +------+------+------+------+------------------...

我有使用二進制協議創建數據包的經驗,例如:

NSUInteger INT_32_LENGTH = sizeof(uint32_t);

uint32_t length = [data length]; // data is an NSData object

NSMutableData *packetData = [NSMutableData dataWithCapacity:length + (INT_32_LENGTH * 2)];
[packetData appendBytes:&requestType length:INT_32_LENGTH]; 
[packetData appendBytes:&length length:INT_32_LENGTH];                  
[packetData appendData:data];                                           

所以我的問題是,您將如何為Axon請求創建數據包,我假設會發生一些移位,但我對此不太了解。

分配1個char數組或大小為== packet_size的無符號char; 十進制常量:

const int metaFieldPos = 0;
const int sizeofMetaField = sizeof(char);
const int lengthPos = metaFieldPos + sizeofMetaField;
const int sizeofLengthField = sizeof(char) * 3;
const int dataPos = lengthPos + sizeofLengthField;

如果獲得了數據並且可以識別數據包的開頭,則可以使用上述常量通過指針進行導航。

也許這些功能會幫到您(它們使用Qt,但是您可以輕松地將它們轉換為您使用的庫)

quint32 Convert::uint32_to_uint24(const quint32 value){
    return value & (quint32)(0x00FFFFFFu);
}

qint32 Convert::int32_to_uint24(const qint32 value){
    return value & (qint32)(0x00FFFFFF);
}

quint32 Convert::bytes_to_uint24(const char* from){
    quint32 result = 0;
    quint8 shift = 0;
    for (int i = 0; i < bytesIn24Bits; i++) {
        result |= static_cast<quint32>(*reinterpret_cast<const quint8 *>(from + i)) << shift;
        shift+=bitsInByte;
    }
    return result;
}

void Convert::uint32_to_uint24Bytes(const quint32 value, char* from){
    quint8 shift = 0;
    for (int i = 0; i < bytesIn24Bits; i++) {
        const quint32 buf = (value >> shift) & 0xFFu;
        *(from + i) = *reinterpret_cast<const char *>(&buf);
        shift+=bitsInByte;
    }
}

QByteArray Convert::uint32_to_uint24QByteArray (const quint32 value){
    QByteArray bytes;
    bytes.resize(sizeof(value));
    *reinterpret_cast<quint32 *>(bytes.data()) = value;
    bytes.chop(1);
    return bytes;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM