mercredi 21 janvier 2015

generate positive random number and right shift by 8 bits and store in a byte

I am struck at writing a java equivalent code for a C code to generate random number. The C code is as follows : static void lng_cosem_CreateRandom(u8 *u8p_Array_p, u8 u8_Len_p) { u8 u8_Indx; u32 u32_Temp;



#if ( _COMPILER_MICROSOFT_VC == LNG_COMPILER_USED )
srand(GetTickCount());
#endif /* LNG_COMPILER_USED */
while( u8_Len_p )
{
u32_Temp = SYS_GetRandom32();
for( u8_Indx = 0; u8_Indx < 4; u8_Indx++ )
{
*u8p_Array_p++ = (u8)u32_Temp;
u32_Temp >>= 8;
u8_Len_p--;
if( !u8_Len_p )
{
break;
}
}
}
}


I wrote a Java equivalent code to the above as follows :



public static void CreateRandom(byte[] COSEM_CTOS, byte
COSEM_CHALLENGE_LEN)
{
long temp;
int index;
pos = 0;
while(COSEM_CHALLENGE_LEN!=0)
{
Random rand = new Random();
temp = Math.abs(rand.nextInt());
System.out.println(temp + "absolute val");
for(index=0;index<4;index++)
{
COSEM_CTOS[pos++] = (byte) temp;
temp >>= 8;
System.out.println(temp + "right shift value");
COSEM_CHALLENGE_LEN--;
if(COSEM_CHALLENGE_LEN == 0 )
{
break;
}
}
}
}


But i get negative numbers after the right shift operation.I want only positive numbers. How can i do it ?





Aucun commentaire:

Enregistrer un commentaire