I have a file format for storing text of any sort. It's a file format from a company, so I can't change it.
Basically, in the beginning of the file, a series of "string starts on char#", "string length equals" values determines the "address" where a string starts and how many chars I shall count to get it. (There's a whole document to explain it; I've attached it to the message).
Something like this:
0 4
4 4
8 9
BirdBookTelephone
So, "Bird" starts on position 0 and has 4 chars; "Book" starts on position 4 and has 4 chars; "Telephone" starts on position 8 and has 9 chars; and so on.
Positions and lengths are stored in binary format, so when you open the file, you can't read them.
To "translate" them, I use the following function:

inline dWord string2Int(string str) // dWord == unsigned int
{
        return *reinterpret_cast<dWord*>(const_cast<char*>(str.data()));
}

That works TO READ the values from a given string. But now I have to do the opposite: change a readable int, turn it into binary little-endian and return the value as a string.

inline string int2String(dWord n)
{
        return ?????????????;
}

How do I do that????

Recommended Answers

All 3 Replies

If the program runs on a little-endian computer:

inline
std::string int2String(dWord n) // unsafe programming
{
    char* p = reinterpret_cast<char*>(&n);
    return std::string(p,sizeof n);
}

Platform-independent (more precisely, LSB/MSB-independent) code is a few cumbersome...

Apropos, your *reinterpret_cast<dWord*>(...) expression is not portable at all: how about proper (for dWord* pointer) alignment of str.data() pointer?..

Thanks for the answer!

Now, I have two more, very quick:
1. Would that also work for a "float2String" function?
2. I'm really a newbie on C++, so I didn't get what you've said about portabillity on last prase. But I'd be happy to change it if you just give me a suggestion...

1. Would that also work for a "float2String" function?
2. ... But I'd be happy to change it if you just give me a suggestion...

1. Yes, it works for short, long, float & double...
2. Variant(s):

/// w/o test s.size() >= sizeof(dWord)
dWord string2int(const std::string& s)
{
    dWord dw;
    ::memcpy(&dw,s.data(),sizeof dw);
    return dw;
}
// or for any non-class type
template<typename POD>
bool string2pod(const std::string& s, POD& pod)
{
    if (s.size() >= sizeof pod) {
        ::memcpy(&pod,s.data(),sizeof pod);
        return true;
    }
    return false;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.