Mark Bluemel said:
Richard Heathfield wrote:
>jacob navia said:
>>>seema wrote:
Hi all,
How to calculate upper 4 bytes and lower 4 bytes of a value? Can
somebody please explain??
say for example,
unsigned int scnlen_lo;
int scnlen_hi;
unsigned long long scnlen;
scnlen=888888;
scnlen_hi= ??//how to calculate upper 4 bytes of scnlen?
scnlen_lo =?? //how to calculate lower 4 bytes of scnlen??
Assuming sizeof(int)==4 (32 bits)
scnlen_hi=(s cnlen>>32);
scnlen_lo=(s cnlen&0xfffffff f);
Wrong. Your "solution" invokes undefined behaviour.
Would it do anyone any harm if you were to a) explain why this is the
case, and b) explain how to solve the original poster's problem
correctly?
I'll let Mr Navia explain why he's wrong.
Here's a solution that I believe to be correct - I don't have a C99
compiler, so I can't check it (because of the unsigned long long) - but
corrections are most welcome:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int rc = EXIT_SUCCESS;
unsigned int scnlen_lo;
int scnlen_hi;
unsigned long long scnlen;
scnlen = 888888ULL;
/* first ensure that a result is possible */
if(sizeof scnlen_lo < 4 || scnlen_hi < 4)
{
puts("No solution exists.\n");
rc = EXIT_FAILURE;
}
else
{
/* build a mask with all bits set */
unsigned long long mask = -1;
/* we need to shift the mask leftward by 4 bytes,
i.e. 4 * CHAR_BIT */
size_t n = CHAR_BIT;
while(n--)
{
mask <<= 4;
}
/* now we can flip */
mask = ~mask;
/* that gives us half the solution with a simple & */
if(scnlen & mask <= UINT_MAX)
{
scnlen_lo = scnlen & mask;
}
else
{
puts("No solution exists for the low four bytes");
rc = EXIT_FAILURE;
}
/* now we need to go the other way */
mask = -1;
n = CHAR_BIT;
while(n--)
{
mask >>= 4;
}
/* same ol' same ol' */
mask = ~mask;
if(scnlen & mask <= INT_MAX)
{
scnlen_hi = scnlen & mask;
}
else
{
puts("No solution exists for the high four bytes");
rc = EXIT_FAILURE;
}
}
return rc;
}
--
Richard Heathfield <http://www.cpax.org.uk >
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999