That's partly what I meant:
This is closer (but still not 100% right):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
void convert(string input){
cout << "Input: " << input << endl;
unsigned long result = 0;
unsigned long start;
unsigned long mask = 0x7f;
unsigned long msbmask = 0x8000;
stringstream(input) >> hex >> start;
for(int i = 0; i < 4; i++){
long temp = (start & mask); //mask the current byte
result = (temp | result);
mask <<= 7;
start >>= 1;
// temp = (shiftval & msbmask); //add the MSB to
// result = (temp | result);
msbmask <<= 7;
}
cout << "Result: " << result << endl;
}
|
Note, in this version the "for" loop goes around 4 times.
What it does
NOT currently do is test the MSB. You don't need to add or combine this bit with the result. Remember the MSB is used to indicate whether there is a continuation byte. If there is not, you need to break out of the loop.
That's why I suggested using 0x8000. This will test (with the "and" operator) the
next byte. If the bit is not set, the loop can end.
(I deliberately made lines 15 and 16 comment lines, as they were incorrect).
Another thing missing in this version, the first byte (starting from the right, as you are doing here) should
always have a MSB of zero - because this is the end of the string.
Also, the code could be shortened a bit. These two lines:
1 2
|
long temp = (start & mask); //mask the current byte
result = (temp | result);
|
can be merged into one:
|
result |= (start & mask); //mask the current byte
|