org.ttzero.excel.util.HexUtil Maven / Gradle / Ivy
/*
* Copyright (c) 2019-2021, [email protected] All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ttzero.excel.util;
/**
* Hex convert util
*
* @author guanquan.wang at 2021-01-13 23:40
*/
public class HexUtil {
private HexUtil() { }
/**
* Convert an byte value to a hexadecimal string
*
* The result string must be a power of {@code 2}, and the insufficient bits
* will be filled with {@code 0}.
* eq: {@code toHexString(3)} returns {@code 0x03}
*
* @param n byte value
* @return hex string
*/
public static String toHexString(byte n) {
char[] chars = {'0', 'x', '0', '0'};
String s = Integer.toHexString(n & 0xFF).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length());
return new String(chars);
}
/**
* Convert an short value to a hexadecimal string
*
* The result string must be a power of {@code 2}, and the insufficient bits
* will be filled with {@code 0}.
* eq: {@code toHexString(3)} returns {@code 0x03}
*
* @param n short value
* @return hex string
*/
public static String toHexString(short n) {
char[] chars = {'0', 'x', '0', '0', '0', '0'};
String s = Integer.toHexString(n & 0xFF).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length());
s = Integer.toHexString(((n >>> 8) & 0xFF)).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length() - 2);
return new String(chars);
}
/**
* Convert an int value to a hexadecimal string
*
* The result string must be a power of {@code 2}, and the insufficient bits
* will be filled with {@code 0}.
* eq: {@code toHexString(3)} returns {@code 0x03}
*
* @param n int value
* @return hex string
*/
public static String toHexString(int n) {
char[] chars = {'0', 'x', '0', '0', '0', '0', '0', '0', '0', '0'};
String s = Integer.toHexString(n & 0xFF).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length());
s = Integer.toHexString(((n >>> 8) & 0xFF)).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length() - 2);
s = Integer.toHexString(((n >>> 16) & 0xFF)).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length() - 4);
s = Integer.toHexString(((n >>> 24) & 0xFF)).toUpperCase();
s.getChars(0, s.length(), chars, chars.length - s.length() - 6);
return new String(chars);
}
}