开发者

Generic: Version number bit shift routine [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I would like the best routine the community can devise which will p开发者_运维百科rovide a version number string using only 32 bits. The version number will contain three parts: major, minor, and build number. Bonus karma points for answers that include Java source.

Update 1

Ok, so to clear up some confusion the major and minor fields should be represented with one 8-bit byte each and the build number would use the remaining bits. Major: 8 bits Minor: 8 bits Build: 16 bits The byte order will be little endian.

The tags are to denote that an answer in java and / or c++ would be preferred over python, ruby, etc..

Update 2

Example: take an integer (4 bytes) like 101020 and run it through an algormithmic routine to produce an output string like so: 0.1.2

Java Solution


    public static final int versionToInt(int major, int minor, int build) {
        int ver = (major << 24) | (minor << 16) | build;
    return ver;
    }

    public static final String versionToString(int ver) {
        return String.format("%s.%s.%s", ((ver & 0xff000000) >> 24), ((ver & 0x00ff0000) >> 16), (ver & 0x0000ffff));
    }


Java:

class Version
{
    public char major;
    public char minor;
    public short build;

    // And the rest of your class definition ...
}

Edit: So you want to do it with a bit shifts and store it in a 32-bit integer (even though using a class or struct would still use the same amount of storage space)?

An example function in C would be as follows

uint32_t MakeVersionNumber( int8_t major, int8_t minor, int16_t build )
{
   return ((uint32_t)major << 24) | ((uint32_t)minor << 16) | ((uint32_t)build);
}

Edit 2:

Riiight I think i get ya. You have a 32-bit number and you want to get a string. So here is an example in C++:

std::string MakeVersionString( unsigned int ver )
{
    std::stringstream ss;
    ss << ((ver & 0xff000000) >> 24) << "." << ((ver & 0x00ff0000) >> 16) << "." << (ver & 0x0000ffff);
    return ss.str(); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜