简体   繁体   中英

How can I convert const std::vector<unsigned char> to char

What would be the correct way to convert from unsigned char std::vector to char?

void SendSocket(const std::vector<BYTE> &buffer)
{
    int ret;
    const BYTE* bufferPtr = &buffer[0];
    ret = send(_socket, (const char*)bufferPtr, buffer.size(), 0);
}

Assuming that BYTE is a typedef for char (with or without signed or unsigned ), then your code is fine, but slightly more verbose than necessary. The storage used by a vector is required to be a contiguous array, so taking the address of the first element gives you a pointer to that array. Any kind of char has the same layout and alignment as any other kind of char , so the pointer conversion is valid.

The argument to send is const void* , and (more or less) any pointer can be converted to that implicitly, so there's no need to cast:

ret = send(_socket, &buffer[0], buffer.size(), 0);

However, you should check (or otherwise ensure) that buffer isn't empty before using [] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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