c++将字符串转换为字节以通过 tcp 发送
我正在尝试将 28 个字符的字符串发送到远程 IP 地址和端口。我已经使用以下代码片段在 vb.net 中成功完成了此操作:
Dim swon As String = "A55A6B0550000000FFFBDE0030C8"
Dim sendBytes As [Byte]()
sendBytes = Encoding.ASCII.GetBytes(swon)
netStream.Write(sendBytes, 0, sendBytes.Length)
我现在必须将其转换为 c++ 并到目前为止具有以下内容:
char *swon = "A55A6B0550000000FFFBDE0030C8";
array<Byte>^ sendBuffer = gcnew array<Byte>(bufferSize);
sendBuffer = BitConverter::GetBytes( swon );
tcpStream->Write(sendBuffer, 0, sendBuffer->Length);
但我在这一点上陷入困境。我确信我错过了一个简单的语法错误,但我无法弄清楚!
澄清一下,我没有收到错误,但我认为字符串没有正确转换为字节,因为当我转换回来时,我只是得到“01”干杯
, 克里斯
I'm trying to send a 28 character string to a remote ip address and port. I've done this successfully in vb.net using the following code snippets:
Dim swon As String = "A55A6B0550000000FFFBDE0030C8"
Dim sendBytes As [Byte]()
sendBytes = Encoding.ASCII.GetBytes(swon)
netStream.Write(sendBytes, 0, sendBytes.Length)
I now have to convert this across to c++ and have the following so far:
char *swon = "A55A6B0550000000FFFBDE0030C8";
array<Byte>^ sendBuffer = gcnew array<Byte>(bufferSize);
sendBuffer = BitConverter::GetBytes( swon );
tcpStream->Write(sendBuffer, 0, sendBuffer->Length);
but am getting stuck at this point. I'm sure I'm missing a simple syntax error but I can't figure it out!
To clarify, I'm not getting an error, but I don't think the string is being converted to bytes correctly as when I convert back, I just get a '01'
Cheers,
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不明白为什么您不在 ++/CLI 代码中使用完全相同的 .Net 框架类。例如。
System::String
用于swon
、Encoding::ASCII
生成字节数组。您在 VB 中所做的任何操作都可以直接映射到 C++/CLI,而无需使用不同的类 - 这对您来说是最简单的移植。当您在线访问 MSDN 时,只需选择
C++
视图即可获取您想要执行的操作的示例。在此页面上尝试,例如: http:// msdn.microsoft.com/en-us/library/system.text.encoding.ascii.aspxI don't understand why you are not just using the exact same .Net framework classes in your ++/CLI code. eg.
System::String
forswon
,Encoding::ASCII
to produce the array of bytes.Anything you did in VB you can map directly over to C++/CLI without using different classes - that's the easest port for you. When you are in MSDN online, just select the
C++
view to get examples of stuff you want to do. Try that on this page, for example: http://msdn.microsoft.com/en-us/library/system.text.encoding.ascii.aspxSteve 是正确的,相同的逻辑可以在 C++ 中重复。但C++
char*
已经是ASCII,不需要转换。只需要一份副本即可。Steve is correct that the same logic can be duplicated in C++. But the C++
char*
already is ASCII, no conversion is necessary. Just a copy is all that's needed.