簡體   English   中英

在C ++中交織二進制表示的向量

[英]Interweaving vector of binary representations in C++

我在C ++中有一個名為weave的模板化函數,它接受兩個無符號字符並交織它們的二進制擴展並返回一個unsigned short。 它還可以使用兩個無符號短路並交織它們的二進制擴展以返回無符號長整數。 這是我寫的:

template<class Typeout, class Typein>
Typeout weave(Typein lhs,Typein rhs)
{
//Need to check that Typeout contains enough storage to contain 2*Typein:
assert(sizeof(Typeout)>=2*sizeof(Typein));

Typeout weaved = 0;
for(int k=0;k<sizeof(Typein)*8;k++)
{
    //weave in the kth element of rhs and lhs.
    weaved |=(Typeout(rhs & (Typein)(1<<k)) << k)| (Typeout(lhs & (Typein)(1<<k)) << (k+1));
}
return weaved;
};

現在我在編織矢量時遇到了麻煩。 我想編寫一個名為weave的函數,給出一個字符向量交織所有的二進制擴展並返回它。 例如,給定長度為4的無符號字符的向量,它應該交織它們的二進制擴展並返回它的表示。 我想這適用於長度大於8的字符向量,所以我不能再將它們保持在無符號的長整數中。 我想我需要返回一個矢量? 但我不確定如何削減產生的二進制擴展。

我是C ++的新手,所以請隨時更正代碼或給我建議。

提前致謝。

編輯:我想我的問題是錯的(坦率地說,我仍然不能確切地說你的帖子中的實際問題在哪里 )。 如果問題是“我應該把什么作為參數以及我應該返回什么類型?”,也許你應該有一個const T*const std::vector<T>&參數用於輸入而另一個用於輸出而不是返回,這個會避免分配內存所有權問題。

// base case, weave two 8 bit into a 16 bit word.
uint16_t weave(uint8_t a, uint8_t b) {
    uint16_t x = a, y = b;
    x = (x | (x << 4)) & 0x0F0F;
    x = (x | (x << 2)) & 0x3333;
    x = (x | (x << 1)) & 0x5555;

    y = (y | (y << 4)) & 0x0F0F;
    y = (y | (y << 2)) & 0x3333;
    y = (y | (y << 1)) & 0x5555;

    return x | (y << 1);
}

// most useful way in my opinion
// weave bits from two arrays 'a' and 'b' of size n
// into a pre-allocated vector 'out'
void weave(const char* a, const char* b, char* out, size_t n) {
    uint16_t* ret = (uint16_t*) out;

    for(size_t i = 0; i != n; ++i) {
        ret[i] = weave(a[i], b[i]);
    }
}

// template version, for those that like sugar
template<typename OUT, typename IN>
OUT weave(IN a, IN b, size_t n = 1) {
    OUT out;
    weave((char*) &a, (char*) &b, (char*) &out, sizeof(IN)*n);
    return out;
}

如果進入生產代碼, 請勿忘記添加檢查,斷言等。

暫無
暫無

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

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