0

I need to convert const char[] to uint8_t in C++. What is the best method

a)

const uint8_t* a = (const uint8_t*)"string";  // I hate this cast, but it works

b)

const uint8_t* a = reinterpret_cast<const uint8_t*>("string");  // is this OK, is it safe?

Why will this not work?

const uint8_t* a = static_cast<const uint8_t*>("string");  // will not compile
user1135541
  • 1,781
  • 3
  • 19
  • 41
  • 3
    Why is this tagged `C`? – David Schwartz Jun 04 '14 at 20:45
  • Because it is c style string. – user1135541 Jun 04 '14 at 20:46
  • C-style strings are a feature of the C++ language. We don't tag questions based on where things originally came from but based on where they are. – David Schwartz Jun 04 '14 at 20:54
  • possible duplicate of [When should static\_cast, dynamic\_cast, const\_cast and reinterpret\_cast be used?](http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used) – jmstoker Jun 04 '14 at 20:58
  • @jmstoker, I did see that but I wanted input for this specific case. What I am trying to understand is why do I need to use reinterpret_cast to convert a byte to byte? Why is unsigned cannot be implicitly converted to signed? It is the same byte? Also, maybe I should not even use reinterpret_cast at all? What are the dangers of it. – user1135541 Jun 04 '14 at 21:43

1 Answers1

2

The second solution is the "Most Correct" way to do it. The reinterpret_cast will be handled entirely by the compiler and simply point at the resulting bits with a different type. The first solution is old-style and generally should not be used in modern C++.

caskey
  • 12,305
  • 2
  • 26
  • 27