Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char array to unsigned char*

Is there a way to convert char[] to unsigned char*?

char buf[50] = "this is a test"; 
unsigned char* conbuf = // what should I add here
like image 495
TQCopier Avatar asked Feb 09 '11 11:02

TQCopier


2 Answers

Although it may not be technically 100% legal this will work reinterpret_cast<unsigned char*>(buf).


The reason this is not 100% technically legal is due to section 5.2.10 expr.reinterpret.cast bullet 7.

A pointer to an object can be explicitly converted to a pointer to an object of a different type. original type yields the original pointer value, the result of such a pointer conversion is unspecified.

Which I take to mean that *reinterpret_cast<unsigned char*>(buf) = 'a' is unspecified but *reinterpret_cast<char*>(reinterpret_cast<unsigned char*>(buf)) = 'a' is OK.

like image 112
Motti Avatar answered Nov 12 '22 22:11

Motti


Just cast it?

unsigned char *conbuf = (unsigned char *)buf;
like image 41
Dave Avatar answered Nov 13 '22 00:11

Dave