我有8个字段的字符串数组。每个字段8位给我这种类型的单个字符串中的64位内存。我想为此字符串数组创建旋转函数。对于简单的字符串20(在十六进制中),函数RotateLeft(string, 1)给了我40,就像在rotate中一样。最大旋转值是64,则函数必须返回发送的字符串(RotateLeft(string, 64) == string)。我需要左右旋转。我尝试创建这样的东西:

std::string RotateLeft(std::string Message, unsigned int Value){
    std::string Output;
    unsigned int MessageLength = Message.length(), Bit;
    int FirstPointer, SecondPointer;
    unsigned char Char;

    for (int a = 0; a < MessageLength; a++){
        FirstPointer = a - ceil(Value / 8.);
        if (FirstPointer < 0){
            FirstPointer += MessageLength;
        }
        SecondPointer = (FirstPointer + 1) % MessageLength;

        Bit = Value % 8;
        Char = (Message[FirstPointer] << Bit) | (Message[SecondPointer] & (unsigned int)(pow(2, Bit) - 1));
        Output += Char;
    }
    return Output;
}

它适用于值64,但不适用于其他值。为了简化HEX字符串(函数将字符串元素获取为十进制值,但为了更好地读取),当我发送以下值时:243F6A8885A308D3并执行RotateLeft(string, 1),我收到了A6497ED4110B4611。当我在Windows Calc中对此进行检查时,它现在是有效值。任何人都可以帮助我并证明我在哪里做错了?

最佳答案

您在字符串中有一个十六进制值,您想像实际是一个数字一样旋转它。您可以将其更改为实际数字,然后重新输入字符串:

// Some example variables.
uint64_t x, shift = 2;
string in = "fffefffe", out;

// Get the string as a number
std::stringstream ss;
ss << std::hex << in;
ss >> x;

// Shift the number
x = x << shift;

// Convert the number back into a hex string
std::ostringstream ss2;
ss2 << std::hex << x;

// Get your output.
out = ss2.str();

Here is a live example.

关于c++ - C++中的字符串旋转器(按位旋转),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33880096/

10-12 00:23
查看更多