2

I need to write 16-bit integers to a file. fstream only writes characters. Thus I need to convert the integers to char - the actual integer, not the character representing the integer (i.e. 0 should be 0x00, not 0x30) I tried the following:

char * chararray = (char*)(&the_int);

However this creates a backwards array of two characters. The individual characters are not flipped, but the order of the characters is. Thus I created this function:

   char * inttochar(uint16_t input)
{
    int input_size = sizeof(input);
    char * chararray = (char*)(&input);
    char * output;
    output[0]='\0';
    for (int i=0; i<input_size; i++)
    {
        output[i]=chararray[input_size-(i+1)];
    }
    return output;
}

This seems slow. Surely there is a more efficient, less hacky way to convert it?

11
  • You can simply do f << i where f is your ofstream and i is your integer. If you want hex than you can do f << "0x" << std::hex << i. Commented Jan 23, 2016 at 15:41
  • I need to convert it to the the actual integer, not the character representing the integer. That method will turn an integer into the character representing the integer. Commented Jan 23, 2016 at 15:42
  • Voted as off-topic because it's too trivial, a non-problem. Commented Jan 23, 2016 at 15:42
  • @Cheersandhth.-Alf The OP wants to write binary, big-endian (or to be precise, the endianness opposite of that native to their machine). Your proposal would produce text. Commented Jan 23, 2016 at 15:42
  • 1
    A bit more compact: char arr[2] = {the_int / 256, the_int % 256}; stream.write(arr, 2); Commented Jan 23, 2016 at 15:46

1 Answer 1

2

It's a bit hard to understand what you're asking here (perhaps it's just me, although I gather the commentators thought so too).

You write

fstream only writes characters

That's true, but doesn't necessarily mean you need to create a character array explicitly.

E.g., if you have an fstream object f (opened in binary mode), you can use the write method:

uint16_t s;
...
f.write(static_cast<const char *>(&s), sizeof(uint16_t));

As others have noted, when you serialize numbers, it often pays to use a commonly-accepted ordering. Hence, use htons (refer to the documentation for your OS's library):

uint16_t s;
...
const uint16_t ns = htons(s);
f.write(static_cast<const char *>(&ns), sizeof(uint16_t));
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, by the way - in case anyone else has this problem - I don't think the static cast there works (it doesn't for me at least.) Maybe it should be changed to reinterpret_cast or just (char*)(&ns)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.