byte[] b = new byte[4]; for (int i = 0; i < 4; i++) { int temp = (int) (Math.random() * 256); b[i] = (byte) temp; } 其实这个主要是生成随机数的范围 下面这个也可以 long a=(long)(Math.random()*(Math.pow(2, 32))); System.out.println(Long.toHexString(a)); 你只需要截取它的后32位就行了
public class test7 { public static long random() { long random = (long) (Math.random() * (Math.pow(2, 32))); return random; } public static void main(String[] args) { long a = random(); long b = random(); long c = ((a << 32) | b); System.out.println(Long.toHexString(c)); } } 我返回的是一个long类型,它的后四个字节就是你要的
大神,貌似对了,我自己写的太繁琐了,而且不知道对不。 byte b = 0; // for ( int i = 0; i <= 0xff; ++i ) // { // b = (byte)i; // System.out.print(" "+i+":"); // int n=b; // System.out.print((char)n); // if((i+1)%10==0){ // System.out.println(); // } // }
所以写了一个,不知道符合不
package cn.test;public class Test{
public static void main(String[] args) {
double d=Math.random();//这个方法循环4遍就生成4个8位的数了。
int i=(int) (d*100000000);
System.out.println("i为:");
System.out.println(i);
}
}
for (int i = 0; i < 4; i++) {
int temp = (int) (Math.random() * 256);
b[i] = (byte) temp;
}
其实这个主要是生成随机数的范围
下面这个也可以
long a=(long)(Math.random()*(Math.pow(2, 32)));
System.out.println(Long.toHexString(a));
你只需要截取它的后32位就行了
long random = (long) (Math.random() * (Math.pow(2, 32)));
return random;
} public static void main(String[] args) {
long a = random();
long b = random();
long c = ((a << 32) | b); System.out.println(Long.toHexString(c));
}
}
我返回的是一个long类型,它的后四个字节就是你要的
byte b = 0;
// for ( int i = 0; i <= 0xff; ++i )
// {
// b = (byte)i;
// System.out.print(" "+i+":");
// int n=b;
// System.out.print((char)n);
// if((i+1)%10==0){
// System.out.println();
// }
// }
System.out.printf("0x%02x",random.nextInt(256));
public static String getRandom(){
java.util.Random random=new Random();
return String.format("0x%02x",random.nextInt(256));
}
package com.aa;
public class ZiJi {
/**
*生成四个随机字节,每个字节的范围均是0x00-0xFF
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
byte[] b=new byte[2];
char[] a={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
for(int t=0;t<4;t++){
String s="Ox";
for(int i=0;i<b.length;i++){
int c=(int) Math.floor(Math.random()*16);
s+=a[c];
}
System.out.println(s);
}
System.out.println();
}
}
//生成的结果是四个随机数 结果举例为:Oxc3 Oxb5 Oxff Ox35