我对为 C 代码编写一个 java 等效代码以生成随机数感到震惊。C 代码如下: static void lng_cosem_CreateRandom(u8 *u8p_Array_p, u8 u8_Len_p) { u8 u8_Indx; u32 u32_Temp;
srand(GetTickCount());
#endif /* ABC_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;
}
}
}
}
我为上面写了一个Java等效代码,如下所示:
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;
}
}
}
}
但是我在右移操作后得到负数。我只想要正数。我该怎么做 ?
好的,现在我已经修改了代码。但是我得到了负随机数。请建议对代码进行如下更改
public static void CreateRandom(byte[] COSEM_CTOS, byte COSEM_CHALLENGE_LEN)
{
ByteBuffer b = ByteBuffer.allocate(4);
byte[] temp = b.array();
int index;
pos = 0;
while(COSEM_CHALLENGE_LEN!=0)
{
Random rand = new Random();
rand.nextBytes(temp);
for(index=0;index<4;index++)
{
COSEM_CTOS[pos++] = temp[index];
COSEM_CHALLENGE_LEN--;
if(COSEM_CHALLENGE_LEN == 0 )
{
break;
}
}
/* or we can use Math.abs(rand.nextByte(COSEM_CTOS)); */
}
}
enter code here