go等价于c类型
go equivalents of c types
围棋中unsigned char
或unsigned 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++的代码更简单,或者至少更容易理解。
相关文章:
- c++ AVX512 本质上等价于 _mm256_broadcast_ss()?
- 等价于将c++上的char赋值给c#
- C++中的数据类型相当于 vb6 中的常量货币
- 什么是提升等价于标准::可选空选项
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 类型依赖于可变参数模板的类
- 如何在未评估的上下文中将成员函数的结果类型应用于类成员
- 什么是 gtkmm 等价于 g_signal_handlers_block_by_func()
- 等价于元组的std::转换
- 等价于C++中的Java静态方法
- Averageif函数等价于C++
- C++等价于Java导入等问题
- C++等价于从C#中选择XML节点
- C等价于新对象(构造函数)
- C++等价于在python中传递lambda函数作为参数
- Microtime()等价于C和C++
- go等价于c类型
- C++使变量类型依赖于用户输入
- 等价于使用Lua_newsthread在C++中创建Lua协程
- Haskell等价于c++类型对