C++ 中几种数据类型转换

C++ 中经常会需要数据类型转换,比如int ->char,CString 到string char->uchar 等等。

//unicode 字符集下 CString 转 string
void UStrToAscChar(const CStringW cs, char *buff)
{
    int n = WideCharToMultiByte(CP_ACP, 0, cs, -1, NULL, 0, NULL, NULL);
    if (n <= 0)
        buff = NULL;
    buff = new char[n];
    memset(buff, 0, n);
    WideCharToMultiByte(CP_ACP, 0, cs, -1, buff, n, NULL, NULL);
}


// string 转CString   
CString cs_str(str.c_str());

解释下:因为在unicode字符集下,CString 默认为宽字符,而string 中的字符默认为单字节字符,即常规的ASCII编码。有的方法说可以用CString的成员函数GetBuffer()实现,但该方法仅限于在多字符集下有效,而MFC却只能在unicode字符集下进行编译,不过也可以下载微软额外的扩展库进行解决。

第一种int<->char 相互转换(该方法是字符型填充,比如 int x= 4658->char a[]= “4658”; char a=[] “4658” ->int x=4658)

//int ->char 
int data_size = 5401;
char buf1[4] = {0};
sprintf(buf1, "%d", data_size); //将data_size写入buf1[]
// char ->int 
int size;
sscanf(buf1,"%d",&size); //将 字符串buf1以整型格式读入size

第二种int ->char 转换(二进制方式)

int i = 796582;
char buf1[4] = { 0 };
// int->char[]
buf[0] = (char)(0xff & i);
buf[1] = (char)((0xff00 & i) >> 8);
buf[2] = (char)((0xff0000 & i) >> 16);
buf[3] = (char)((0xff000000 & i) >> 24);

//char[]->int 
//如果你用的编译器默认char为 有符号的,注意要将char[]->uchar[]->int
//如果编译器默认char为 无符号的,则可以直接转
uchar buf2[] = { 0 };
for(int i = 0;i < 4; i++)
{
    buf2[i] = buf1[i];
}
int j = (int)((buf2[0]) | ((buf2[1]) << 8) | ((buf2[2]) << 16) | ((buf2[3]) << 24));
//另外,如果将包含0的char[]送到string中,则char[]中的0元素会自动抹
//掉,这点在网络传输的包头中要注意。如果实在需要保留char[]中的0元素,//可以按字节赋值

string str(4,'0');
for(int i = 0;i < 4; i++)
{
    str[i] = buf1[i];
}

图像数据Mat 与vector 之间的转换

// Mat convert to byte array
vector<byte> CWatchFaceDlg::Matconvbyte(Mat img)
{
    int a, b;
    a = img.total();
    b = img.elemSize();
    int size = a*b;
    std::vector<byte> img_bytes(size);
    img_bytes.assign(img.datastart, img.dataend);
    return img_bytes;
}
// byte array  convert to Mat 
cv::Mat CWatchFaceDlg::BytestoMat(std::vector<byte>bytes, int height, int width)
{
    cv::Mat img = cv::Mat(height, width, CV_8UC3, bytes.data()).clone();
    return img;
}

string -> vector 之间的转换

// string convert to byte array
std::vector<byte> CWatchFaceDlg::stringtobyte(string str)
{
    int size = str.size();
    std::vector<byte> bytes(size);
    bytes.assign(str.begin(), str.end());
    return bytes;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值