简体   繁体   English

C ++:将int转换为unsigned char

[英]C++: covert int to unsigned char

I declared an IP address: 我声明了一个IP地址:

int test_ip = (192) | (168<<8) | (33<<16) | (255<<24);

Then I need to convert it to (unsigned char*). 然后,我需要将其转换为(unsigned char *)。 I trying to do this: 我试图这样做:

(u_char*)test_ip

I use VS 2010 C++ debugger in order to evaluate the last expression. 我使用VS 2010 C ++调试器来评估最后一个表达式。 Debugger's output for this expression: 该表达式的调试器输出:

0xff21a8c0 <Bad Ptr>

What am I doing wrong? 我究竟做错了什么? Why Bad Ptr? 为什么选择不良Ptr?

Your conversion better be done by in_addr data type: 最好通过in_addr数据类型完成转换:

This is the windows in_addr so if you want to use it on linux you'll have to re-declare it with other name. 这是Windows in_addr,因此如果要在linux上使用它,则必须使用其他名称重新声明它。

typedef struct in_addr {
  union {
    struct {
      u_char s_b[4];
    } S_un_b;
    struct {
      u_short s_w[2];
    } S_un_w;
    u_long S_addr;
  } S_un;
};

like this: 像这样:

in_addr address;
address.S_addr = (192) | (168<<8) | (33<<16) | (255<<24);

address.S_un_b.s_b is ready now, with array of 4 bytes representing the address... address.S_un_b.s_b现在已经准备好,其中4个字节的数组表示地址...

Attempting a c-style cast will give you undefined behaviour as the pointer types are unrelated. 由于指针类型无关,尝试c样式强制转换将给您未定义的行为。 Your best bet is to use a static cast of the int, modulo 256. 最好的选择是使用int的静态转换,以256为模。

unsigned char c = static_cast<unsigned char>(test_ip % 256)

This will be safe since the standard guarantees the size of an unsigned char as being 8 bits. 这是安全的,因为该标准保证无符号字符的大小为8位。

Once you've taken this cast to unsigned char, take the address of that as your pointer &c. 一旦将此强制转换为无符号字符,请将其地址作为指针&c。

If you want other parts of test_ip then combine with integral division etc. Just take care not to overflow the unsigned char when taking the cast. 如果要test_ip的其他部分,则与整数除法等结合。请注意在进行强制转换时不要溢出未签名的char。

Presumably, you need it as an unsigned char* to pass it to some protocol. 大概,您需要将它作为unsigned char*才能传递给某些协议。 In which case, you can't just cast, since the bit representation of your int is not necessarily what the protocol expects. 在这种情况下,您不能只是强制转换,因为int的位表示不一定是协议所期望的。 You have to extract it byte by byte, just as you constructed it, placing the bytes in an unsigned char buffer. 您必须像构造它一样逐个字节地提取它,并将这些字节放置在unsigned char缓冲区中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM