Question

My question is in the following example what does val = val >> 2; do? That is I believe it is division by 4.

int val = 12345678;
val = val >> 2;

Here is the background to this question.

I have a read from a water meter, say 12345678. The way our water meters work is the two right-hand digits are thrown away for the read, so 123456 is really the read. (There are reasons for throwing away the two right hand digits that have to do with how water flow makes the registers turn. That really has nothing to do with my question, though.)

Currently, we are taking 12345678 and dividing it by 100, using 4GL integer variables, so I'm not getting a decimal number. We are getting truncation we do not expect, and I am trying to determine if bit shift would be better.

After the read is truncated to 123456, a delta is calculated using the last read (also truncated), and from that the consumption is generated.

I have C available to me in Informix 4GL, and I believe the best way to remove the lowest two digits would be to bit-shift right by 2. I believe that is the only way I am going to obtain -- for example --

5 digit meter   12345 --> 123
6  "     "     123456 --> 1234
7  "     "    1234567 --> 12345

Thank you for tolerating a simplistic question. We're trying to figure out a problem of how are endpoints -- which talk to the meters -- are programmed and what the data really means coming out of the endpoints.

Était-ce utile?

La solution

Bit-shifting throws away the last two binary digits, not decimal digits. It is equivalent to integer division by four. You need to int-divide by 100 to throw away the last two decimal digits.

101111000110000101001110bin = 12345678dec

101111000110000101001110bin >> 2dec = 1011110001100001010011bin

1011110001100001010011bin = 3086419dec

Autres conseils

'>>' performs a bitwise shift operation.

To understand what it does, you'd first convert 12345678 to binary.

12345678 = 100101101011010000111

'>>' means you shift each bit to the right, and in your example, 2 places. (<< shifts to the left)

100101101011010000111 >> 2 = 001001011010110100001

Then convert back to decimal: 308641

12345678       : 101111000110000101001110
12345678 >> 2  : 1011110001100001010011
12345678 / 4   : 1011110001100001010011

Within i4gl, you can easily cast the digits into a CHAR, truncate it [1,6], then cast it back to INT.

EDIT: See Type conversion in i4gl

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top