欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++ Convert struct to bytes

程序员文章站 2022-04-20 19:16:22
D:\stock\Tskingfromgoogle\src\NetTS\TW.cpp Convert struct to bytes ......

d:\stock\tskingfromgoogle\src\netts\tw.cpp

convert struct  to bytes

//convert struct  to bytes 2019/05/20 by freeman
int constructloginbuffer(byte* buffer, size_t maxlen, lpctstr lpszuser, lpctstr lpszpasswd)
{
	int nlen = 0;
	int nlenuser = strlen(lpszuser);
	int nlenpasswd = strlen(lpszpasswd);

	tw_login	packet;
	memset(&packet,0,sizeof(packet));
	packet.m_header.m_magic = tw_magic;
	if(maxlen < (int)(5 + sizeof(tw_header) + nlenuser + nlenpasswd))
	{
		nlen = 5 + sizeof(tw_header);
		return -1;
	}
	packet.m_name_len = (word)nlenuser;
	memcpy(packet.m_data, lpszuser, nlenuser);
	*(word*)(packet.m_data + nlenuser)	=	(word)nlenpasswd;
	memcpy(packet.m_data + nlenuser + sizeof(word), lpszpasswd, nlenpasswd);

	nlen = 5 + sizeof(tw_header) + nlenuser + nlenpasswd;
	constructlength(packet.m_header, nlen - sizeof(packet.m_header));

	if(buffer)
		memcpy(buffer, &packet, nlen);
	return nlen;
}