Here you can find the source of toHex(int n, int bytes)
Parameter | Description |
---|---|
n | The number to convert |
bytes | The number of bytes to convert (1-4) |
public static String toHex(int n, int bytes)
//package com.java2s; // in accordance with the terms of the license agreement accompanying it. public class Main { private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /**/*from ww w. ja va2 s . c o m*/ * Converts the given number into a hex string * @param n The number to convert * @param bytes The number of bytes to convert (1-4) * @return The number represented in hex */ public static String toHex(int n, int bytes) { // Sanity check the number of bytes if ((bytes < 1) || (bytes > 4)) { bytes = 4; } StringBuffer sb = new StringBuffer(); for (int i = (bytes - 1); i >= 0; i--) { sb.append(hexDigit[(n >> ((i * 8) + 4)) & 0x0F]); sb.append(hexDigit[(n >> (i * 8)) & 0x0F]); } return sb.toString(); } /** * Converts the given number into a hex string. The number * is assumed to be a 4-byte int * @param n The number to convert * @return The number represented in hex */ public static String toHex(int n) { return toHex(n, 4); } }