Home > Blockchain >  How to Compare the Numerical value of the Second-lowest Byte of L to the Second Lowest Byte of M
How to Compare the Numerical value of the Second-lowest Byte of L to the Second Lowest Byte of M

Time:09-19

How to Compare the Numerical value of the Second-lowest Byte of L to the Second Lowest Byte of M?

I have a pseudo-random number generator, but I am unsure how to sort the bytes. I need to find the second lowest byte of "L" and "M" and then increment the value of the variable "lHigh" or "mHigh" depending on which one has the greater "second-lowest" byte.

So, for example, the second-lowest Byte of the 32-bit Hex number 0xAABBCCDD would be the “CC” value.

If L is higher than M i would want to increment the variable "lHigh"

So basically, I am comparing bits 8-15 of L to bits 8-15 of M.

CodePudding user response:

With unsigned values and lowest means least significant: the 2nd least significant bytes are

#include <limits.h>
unsigned char L2 = L >> CHAR_BIT;
unsigned char M2 = M >> CHAR_BIT;

// Form a 1,0,-1 depending on compare result.
int compare = (L2 > M2) - (L2 < < M2);

CodePudding user response:

To elminate the bits of the "lowest byte" so they have no consequence you can 'knock those bits down' by ANDing with the one's complement of 0xFF.
( x & ~0xFF )

Below, two integer values are shown and then compared.

int mmain() {
    // test 5 values crossing a threshold
    for( int i = 0; i < 5; i   ) {
        int x = (1 << 8)   254; // a start with 1 in "2nd lowest byte"
        int y = (1 << 8)   4;

        x  = i; // "lowest byte" of 'x' increases on each loop

        // show values
        printf( "%d : x(%d) y(%d) :: special-x(%d) special-y(%d) :: ",
            i, x, y, x&~0xFF, y&~0xFF );

        // show comparison
        puts( (x&~0xFF) == (y&~0xFF) ? "x==y" : "x > y" );
    }

    return 0;
}

Output

0 : x(510) y(260) :: special-x(256) special-y(256) :: x==y
1 : x(511) y(260) :: special-x(256) special-y(256) :: x==y
2 : x(512) y(260) :: special-x(512) special-y(256) :: x > y
3 : x(513) y(260) :: special-x(512) special-y(256) :: x > y
4 : x(514) y(260) :: special-x(512) special-y(256) :: x > y
  • Related