您的位置:首页 > 编程语言 > C语言/C++

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

2016-11-15 22:28 645 查看
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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string cstring