Java: BigInteger & 整形 <=> byte[]
阿新 • • 發佈:2022-04-22
package io.wig; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Arrays; public class Fozy{ public static void main(String[] args){ SecureRandom secureRandom = new SecureRandom(); byte[] bytes = new byte[16]; secureRandom.nextBytes(bytes); System.out.println("bytes = " + Arrays.toString(bytes)); BigInteger bigInt = new BigInteger(1, bytes); System.out.println("bigInt = " + bigInt); System.out.println("bigInt.toByteArray() = " + Arrays.toString(bigInt.toByteArray())); System.out.println("toByteArray(bigInt) = " + Arrays.toString(toByteArray(bigInt))); BigInteger bigInteger= new BigInteger(bytes); System.out.println("bigInteger = " + bigInteger); System.out.println("bigInteger.toByteArray() = " + Arrays.toString(bigInteger.toByteArray())); } public static byte[] toByteArray(BigInteger bigInteger){ byte[] bytes = bigInteger.toByteArray(); byte[] tmp = newbyte[bytes.length - 1]; System.arraycopy(bytes,1,tmp,0,tmp.length); return tmp; } }
int => byte[] Big Endian
public class Cozy{ public static void main(String[] args){ byte[] bytes = intToByteBig(0xFF); System.out.println("b1 = " + Arrays.toString(bytes)); } public static byte[] intToByteBig(int n){ byte[] bytes = new byte[4]; int length = bytes.length; for(int b = 0; b < length; ++b){ bytes[length - 1 - b] = (byte) (n >> b * 8 & 0xFF); } return bytes; } }
int => byte[] Little Endian:
import java.util.Arrays; public class Cozy{ public static void main(String[] args){ byte[] bytes = intToByteLittle(0xFF); System.out.println("b1 = " + Arrays.toString(bytes)); } public static byte[] intToByteLittle(int n){ byte[] bytes = new byte[4]; int length = bytes.length; for(int b = 0; b < length; ++b){ bytes[b] = (byte) (n >> b * 8 & 0xFF); } return bytes; } }
byte[] => int Big Endian:
public class Cozy{ public static void main(String[] args){ int i = bytesToIntBig(new byte[]{0, -1, -1, -1}); System.out.println("i = " + i); } public static int bytesToIntBig(byte[] bytes){ int n = 0; int length = bytes.length; for(int b = 0; b < length; ++b){ n |= (bytes[b] & 0xFF) << 8 * (length - 1 - b); } return n; } }
byte[] => int Little Endian:
public class Cozy{ public static void main(String[] args){ int i = bytesToIntLittle(new byte[]{0, -1, -1, -1}); System.out.println("i = " + i); } public static int bytesToIntLittle(byte[] bytes){ int n = 0; int length = bytes.length; for(int b = 0; b < length; ++b){ n |= (bytes[b] & 0xFF) << 8 * b; } return n; } }