我想知道char变量的每个int值... [英] I want to know the each int value to char variable...
问题描述
例如:
CString ip_address = _T(192.168.0.213);
我想知道要移动的方法每个char值为192,168,0,213的每个char变量大小为1.
喜欢这个:
char ipaddr [4];
ipaddr [0] = 192;
ipaddr [1] = 168;
ipaddr [1] = 0;
ipaddr [1] = 213;
是的,我真正知道的是数据类型转换CString(或char字符串)的方法
整数变量。
谢谢。
我尝试了什么:
在这个晚上,这个问题浪费了3-4个小时。
For example:
CString ip_address = _T("192.168.0.213");
I want to know the method to move each int value 192,168,0,213 to each of char variable with size 1.
Like this:
char ipaddr[4];
ipaddr[0] = 192;
ipaddr[1] = 168;
ipaddr[1] = 0;
ipaddr[1] = 213;
Yes, What I really know is the method of the datatype conversion CString(or char string) to
integer variables.
Thank you.
What I have tried:
In this evening, 3-4 more hours wasted for this problem.
推荐答案
这个已经多次询问和回答。这只是找到正确搜索词的问题。我使用了c ++ parse ip string并得到了很多有用的结果:
C ++如何将ip地址转换为字节? - 堆栈溢出 [ ^ ]
c - 以4个单字节解析ip地址字符串 - Stack Overflow [ ^ ]
一旦选择了解析方法,就必须注意到你的字符串是CString
(TCHAR *
)。因此,请使用C标准库的_t *
版本(例如_stscanf
)。因为大多数字符串到整数转换返回一个整数,所以在分配时必须将它们转换为字节。
使用sscanf的示例
/_stscanf
:
This has been asked and answered multiple times. It is just a question of finding the correct search term. I used "c++ parse ip string" and got a lot of useful results:
C++ how to convert ip address to bytes? - Stack Overflow[^]
c - parsing ip adress string in 4 single bytes - Stack Overflow[^]
Once you have choosen a parsing method you must observe that your string isCString
(TCHAR *
). Therefore, use the_t*
versions of the C standard library (e.g._stscanf
). Because most string to integer conversions return an integer, you must cast them to bytes when assigning.
Example usingsscanf
/_stscanf
:
unsigned short a, b, c, d;
// May check the return value here (should be 4) for basic validity check
_stscanf(ip_address.GetString(), _T("%hu.%hu.%hu.%hu"), &a, &b, &c, &d);
unsigned char ipaddr[4];
ipaddr[0] = static_cast<unsigned char>(a);
ipaddr[1] = static_cast<unsigned char>(b);
ipaddr[2] = static_cast<unsigned char>(c);
ipaddr[3] = static_cast<unsigned char>(d);
有几种方法可以完成这样的任务。例如,您可以使用 Tokenize [ ^ ]方法提取octects的所有(字符串表示)然后转换每个字符串到相应的字节(例如使用 itoa [ ^ ]。
There are several ways to accomplish such a task. You can, for instance, use the Tokenize[^] method to extract all (the string representations of) the octects ant then convert each string to the corresponding byte (e.g. using itoa[^]).
拆分每个字符串逗号,并使用您已经知道的每个部分的数据类型转换。然后将整数值转换为一个字节(或unsigned char)并将四个元素分配给你的ipaddr数组。
但是不要将它声明为char - 这是一个带符号的7位数量和IP地址元素是无符号的8位值,应该这样处理。
小错别字[/ edit]
Split the string at each comma, and use the datatype conversion you already know about on each part. Then just cast the integer value to a byte (or unsigned char) and assign to the four elements to your ipaddr array.
But don't declare it as char - that's a signed 7 bit quantity and IP address elements are unsigned 8 bit values and should be treated as such.
[edit]Minor typos[/edit]
这篇关于我想知道char变量的每个int值...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!