去等同于c类型

时间:2015-02-16 19:31:12

标签: c++ go

go中unsigned charunsigned char*的正确等价物是什么?或者我甚至做得对吗?


我有这个C ++类:

class ArcfourPRNG
{
public:
    ArcfourPRNG();
    void SetKey(unsigned char *pucKeyData, int iKeyLen);
    void Reset();
    unsigned char Rand();

private:
    bool m_bInit;
    unsigned char m_aucState0[256];
    unsigned char m_aucState[256];
    unsigned char m_ucI;
    unsigned char m_ucJ;
    unsigned char* m_pucState1;
    unsigned char* m_pucState2;
    unsigned char m_ucTemp;
};

我正在尝试将其重写为:

type ArcfourPRNG struct {
    m_bInit bool
    m_aucState0 [256]byte
    m_aucState [256]byte
    m_ucI, m_ucJ []byte
    *m_pucState1 []byte
    *m_pucState2 []byte
    m_ucTemp []byte
}

func (arc4 *ArcfourPRNG) SetKey(pucKeyData []byte, iKeyLen int) {
func (arc4 *ArcfourPRNG) Reset() {
func (arc4 *ArcfourPRNG) Rand() uint {

好吧,我刚开始几个小时前去。所以这仍然令我感到困惑。


功能

for(i=0; i<256; i++)
{
    m_pucState1 = m_aucState0 + i;
    m_ucJ += *m_pucState1 + *(pucKeyData+m_ucI);
    m_pucState2 = m_aucState0 + m_ucJ;
    //Swaping
    m_ucTemp = *m_pucState1;
    *m_pucState1 = *m_pucState2;
    *m_pucState2 = m_ucTemp;
    m_ucI = (m_ucI + 1) % iKeyLen;
}
memcpy(m_aucState, m_aucState0, 256); // copy(aucState[:], aucState0) ?

1 个答案:

答案 0 :(得分:2)

希望这可以为您解决一些问题。

  • 要存储原始字节序列,请使用片[]byte。如果你确切地知道序列的长度,你可以指定,例如[256]byte但你以后无法调整大小。
  • 虽然Go有指针,但它没有指针算术。因此,您需要使用整数来索引您的字节片段。
  • 为了存储单个字节,byte就足够了;你不想要一块字节。如果C ++代码中的指针用于指向数组中的特定位置,那么您只需要一个整数索引值来选择切片中的一个元素。
  • Go字符串只是字节序列,它们是内部存储为符文的UTF-8字符序列,它们可能具有不同的长度。因此,请勿尝试使用此算法的字符串。

要重新实现所示的算法,根本不需要指针或指针算法。您不必像在C ++中那样保持指向字节数组的指针,而是将int索引用于切片。

这很难理解,因为它实际上是所有指针算法。我希望在转换它时能够对算法进行简单的描述(因为这可能是一个众所周知的算法,不应该很难找到)。我不打算为你做整个转换,但我希望能够展示一个更简单的例子。这会在单独的行上打印字符串的每个字符。

C ++:

unsigned char *data = "Hello World";
unsigned char *ptr = 0;

for (int i = 0; i < std::strlen(data); i++) {
    ptr = i + data;
    std::cout << *ptr << std::endl;
}

转到:

data := []byte("Hello World")

for i := 0; i < len(data); i++ {
    // The pointer is redundant already
    fmt.Println(data[i:i+1])
}

所以,learn about Go slices,当你重新实现这个算法时,你可能会发现代码比它的C ++版本更简单,或者至少更容易理解。