简体   繁体   English

优化基准之间的转换-C ++

[英]Optimizing conversion between bases - C++

I am designing a cipher and need to convert between bases repeatedly in a loop. 我正在设计一个密码,需要在一个循环中在碱基之间重复转换。 I have optimized the everything else, but I'm not too familiar with C++ code, and and am trying to figure out how to make the conversion faster. 我已经优化了其他所有内容,但是我对C ++代码不太熟悉,并且正在尝试找出如何使转换更快。

Here's the current code I'm using: 这是我正在使用的当前代码:

string digits = "0123456789abcdef";
string tohex(string number) {                        // Decimal to Hexadecimal function
    long length = number.length();
    string result = "";
    vector<long> nibbles;
    for ( long i = 0; i < length; i++ ) {
        nibbles.push_back(digits.find(number[i]));
    }
    long newlen = 0;
    do {
        long value = 0;
        newlen = 0;
        for ( long i = 0; i < length; i++ ) {
            value = (value * 10) + nibbles[i];
            if (value >= 16) {
                nibbles[newlen++] = value / 16;
                value %= 16;
            } else if (newlen > 0) {
                nibbles[newlen++] = 0;
            };
        };
        length = newlen;
        result = digits[value] + result;
    } while (newlen != 0);
    return result;
}

In my case (cipher) the number will always fit within an int, so it works to do: 在我的情况下(密码),该数字将始终位于一个int内,因此可以这样做:

string tohex(string number) {
    int num = std::stoi(number);
    std::stringstream hexnumber;
    hexnumber << std::hex << num;
    return hexnumber.str();
}

This is better because it is simpler and uses the built-in std::hex method. 这样做更好,因为它更简单并且使用内置的std :: hex方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM