Reputation: 2848
I have string array which has 8 field. 8 bits per field give me 64 bits of memory in single string this type. I want to create rotate function for this string array. For simple for string 20
(in HEX) function RotateLeft(string, 1)
gives me 40, like in rotate. Max rotate value is 64, then function must return sent string (RotateLeft(string, 64) == string
). I need rotate left and right. I try to create something like this:
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;
}
It working for value 64, but not for other values. For simple for HEX string (function get string elements as decimal values but it is for better reading) when I sent this value: 243F6A8885A308D3
and execute RotateLeft(string, 1)
I received A6497ED4110B4611
. When I check this in Windows Calc it now valid value. Anyone can help me and show where I do mistake?
Upvotes: 2
Views: 778
Reputation: 122830
I am not sure if I correctly understand what you want to do, but somehow to me it looks like you are doing something rather simple in a complicated way. When shifting numbers, I would not put them in a string. However, once you have it as a string, you could do this:
std::string rotate(std::string in,int rot){
long long int number;
std::stringstream instream(in);
instream >> number;
for (int i=0;i<rot;i++){number *= 2;}
std::stringstream outstream;
outstream << number;
return outstream.str();
}
...with a small modification to allow also negative shifts.
Upvotes: 3
Reputation: 33904
You have a hex value in a string, you want to rotate it as if it was actually a number. You could just change it to an actual number, then back into a string:
// 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();
Upvotes: 2