C++ Can';t从char指针复制到short
我有一个包含以下信息的char指针:C++ Can';t从char指针复制到short,c++,pointers,C++,Pointers,我有一个包含以下信息的char指针: char* data = "22"; 我想把它从char复制到一个短变量中。 我有以下代码: short BinarySerializer::getMessageTypeID(char* data) { short* messageTypeID; memcpy( messageTypeID, data, sizeof( messageTypeID ) ); return *messageTypeID; } 我不知道为什么,但当我打
char* data = "22";
我想把它从char复制到一个短变量中。
我有以下代码:
short BinarySerializer::getMessageTypeID(char* data)
{
short* messageTypeID;
memcpy( messageTypeID, data, sizeof( messageTypeID ) );
return *messageTypeID;
}
我不知道为什么,但当我打印它时,我得到:12850
这就是我打印它的方式:
short temp = msg->messageTypeID;
cout << "Message ID is: " << temp << endl;
short temp=msg->messageTypeID;
也许你指的是以下几点
#include <iostream>
#include <sstream>
#include <numeric>
#include <cstring>
struct BinarySerializer
{
short getMessageTypeID( const char *data ) const;
short getMessageTypeID1( const char *data ) const;
};
short BinarySerializer::getMessageTypeID( const char *data ) const
{
short messageTypeID = 0;
std::istringstream is( data );
is >> messageTypeID;
return messageTypeID;
}
short BinarySerializer::getMessageTypeID1( const char *data ) const
{
short messageTypeID;
messageTypeID = std::accumulate( data, data + std::strlen( data ), ( short)0,
[]( short acc, char c )
{
return 10 * acc + ( c - '0' );
} );
return messageTypeID;
}
int main()
{
const char *s = "22";
std::cout << BinarySerializer().getMessageTypeID( s ) << std::endl;
std::cout << BinarySerializer().getMessageTypeID1( s ) << std::endl;
}
如果数据看起来像“22sdfsd”
。然后,您需要添加将查找第一个非数字值的代码
您还可以使用函数std::strtol
,检查获得的值是否在short类型值的范围内
例如(不检查获取的值是否对类型short有效)
让我们看看内存,假设short的大小是char大小的两倍(情况并非总是如此!):
内存中有带“22”字符串的字符数组:
50 50
所以基本上
00110010 00110010
当您将其存储为一个短字符时,您将得到一个由两个字节组成的数字:
00110010 00110010
翻译成十进制表示12850
现在,我想您真的想要将“22”ascii表转换为“22”值。在这种情况下,您可以参考
如果您确实需要对“23123dsdwqdwqd”之类的字符串的支持(这种情况很少出现),您可以复制所需大小的子字符串并处理该子字符串
<>记住,在变量大小方面,只有C++标准保证的是
sizeof(char) <= sizeof (short) <= sizeof(int) <= sizeof(long)
sizeof(char)“我想把它从char复制到一个短变量中。”不,你很可能想把它转换成一个short
值。这是一个很大的区别。不,我想复制。因为将来我会有更多关于字符数组(指针)的数据。@ShaulZuarets因此,请澄清您对temp
的具体输出预期。我预计输出为22。即使char数组是“22sdfsd”。@ShaulZuarets如前所述,复制也不是正确的方法。您想从一个数据库解析数字。
short BinarySerializer::getMessageTypeID( const char *data ) const
{
short messageTypeID = 0;
messageTypeID = ( short )strtol( data, nullptr, 10 );
return messageTypeID;
}
sizeof(char) <= sizeof (short) <= sizeof(int) <= sizeof(long)