0

Im trying to extract two (int32_t) values, and place them within a char array.

int32_t version = getVersion();

if (version < 0)
{
    return;
}
else
{
    //first part of number needs to be shifted right
    int32_t major = (((version) >>16) & 0xFFFF);
    int32_t minor = ((version) & 0xFFFF);

    // need to concatenate these two values, and place a "." between them

    setVersion(...);//requires a char array, should for example be "1.1"
}

can anyone give me any advice on the best way to do this? without the use of std::strings please. I would prefer a char array.

Thanks in advance

user1381456
  • 27
  • 1
  • 5

2 Answers2

6

You can employ strstream

char v[255] = {};
{
  std::strstream vs(v, 254);
  vs << major << '.' << minor;
}
setVersion(v);
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
0

Here is another way of doing it.

snprintf(charArray, sizeof(charArray), "%d.%d", major, minor);

// Please check the correctness for format specifier and verify the return 
// value too.

If you are on Windows platform, use _snprintf_s.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • that looks good, what size would I be required to make the char array? as im extracting these two value, plus the "."? – user1381456 Jun 30 '12 at 14:23
  • 2
    As in Johannes answer, you need to have some default size with zero initialized. You can count number of digits in major, minor using some logic and set dynamically size of `charArray` accounting for the size of major+dot+minor+null. But that is up to you as to which way to implement. – Mahesh Jun 30 '12 at 14:26
  • I would consider this good advice for C. But for C++ the danger of incorrect types (and there is no need for speed) out ways this as a valid usage. – Martin York Jun 30 '12 at 16:11