Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert F to FF using left shift operator

Tags:

c++

bit-shift

I have UINT64 variable. In start it is initialized to 0xF. Now I want this to change on runtime depending on some input. Its value will increase on runtime. But what I want is that it should change from F to FF, from FF to FFF, one F should be appended to it.

Now here is my code.

UINT64 mapFileSize = 0xF;
while (mapFileSize < someUserInput)
    // add one F to mapFileSize;

What should I write there. I am trying left shift operator but it is not working fine.

mapFileSize <<= 1;

I am doing this but this does not give me desired result.

like image 945
fhnaseer Avatar asked Jan 27 '26 03:01

fhnaseer


2 Answers

leftshift mapFileSize 4 bit

and then or the mapFileSize with 0xF

 mapFileSize = mapFileSize  <<4;
 mapFileSize = mapFileSize  | 0xF;
like image 136
Debobroto Das Avatar answered Jan 28 '26 15:01

Debobroto Das


What you're describing is not the result of a single shift. A << just shifts the bits, shifting in zeros as needed, but you would need to shift in ones which is something C's left-shift operator just doesn't do.

You need to first shift, and then set the lowest four bits to all ones:

mapFileSize <<= 4;  /* Shift to the left one hexadecimal digit. */
mapFileSize |= 0xf; /* Make sure rightmost digit is f. */
like image 29
unwind Avatar answered Jan 28 '26 16:01

unwind