Good day. Tell me how to implement the method of squares means on b. There is an example of a function code on pascal:

var xi: longint; {глобальная переменная; сюда изначально должна быть помещена затравка} function rrsch:real; begin xi:=((xi*xi) shr 7) and $3FFF; {28 бит - квадрат, 14 бит - число} if xi=0 then begin Random( …); {заносит в RandSeed очередное псевдослучайное число - затравку} xi:=RandSeed and $3FFF; end; rrsch:=xi/$4000; {двоичное 01000000 00000000} end; 

If, for example, we take the middle of the square from the number 4824, then 4824 ^ 2 = 23270976 we will need to take 2709 from this number. As I understand it, it should be done with the help of the bit-shift operator, but I failed to realize it.

    1 answer 1

    @Beryllium , as I understand you want to get the middle bits of the piece. Those. for 32-bit integers you need medium 16 bits.

    I do not want to argue about the correctness of the program on pascal, just demonstrate this extraction in an example on C.

     #include <stdio.h> #include <stdlib.h> main () { u_int x = 4824, mid, sqr; sqr = x*x; mid = (sqr>>8) & 0xffff; // вот это Вам и надо делать printf ("x = 0x%x sqr = 0x%x mid = 0x%x\n", x,sqr,mid); exit (0); } 

    In the mid variable you are interested in 16 bits. By the way, all this is visual only in hexadecimal digits.

     avp@avp-ubu1:~/hashcode$ gcc midsqr.c avp@avp-ubu1:~/hashcode$ ./a.out x = 0x12d8 sqr = 0x1631640 mid = 0x6316 avp@avp-ubu1:~/hashcode$ 

    Sorry. Just noticed that you are interested in 14-bit numbers. Then the formula mid = ((x*x) >> 7) & 0x3fff certainly true. This is clearly seen in the binary output.

      x = 4824 & 0x3fff; sqr = x*x; mid = (sqr>>7) & 0x3fff; printf ("x = 0x%x sqr = 0x%x mid = 0x%x\n", x,sqr,mid); char xstr[64], qstr[64], mstr[64]; my_llstr((long long)x,2,0,xstr); my_llstr((long long)sqr,2,0,qstr); my_llstr((long long)mid,2,0,mstr); printf ("x = %s\nsqr = %s\nmid = %s\n", xstr,qstr,mstr); 

    And these are the results (without leading zeros)

     для 28/14 бит: x = 0x12d8 sqr = 0x1631640 mid = 0x62c x = 1001011011000 sqr = 1011000110001011001000000 mid = 11000101100 

    So, do not worry. IMHO you have everything correctly calculated, just a problem with a visual display of the result.

    • Thank! Just what you need. I think with a 32-bit grid it will be even better. - Beryllium