go等价于c类型

go equivalents of c types

本文关键字:类型 等价于 go      更新时间:2023-10-16

围棋中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) ?

希望这能为您澄清一些问题。

  • 要存储原始字节序列,请使用切片[]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;
}

Go:

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

因此,学习Go切片,当你重新实现这个算法时,你可能会发现代码比C++的代码更简单,或者至少更容易理解。