Created
April 19, 2024 01:01
-
-
Save DrBrad/b691c409b45d42851f9331449b32406b to your computer and use it in GitHub Desktop.
Java Number to byte array without using String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static char[] numberToByteArray(int number) { | |
int numDigits = getNumDigits(number); | |
char[] charArray = new char[numDigits]; | |
for (int i = numDigits - 1; i >= 0; i--) { | |
charArray[i] = (char)('0' + number % 10); | |
number /= 10; | |
} | |
return charArray; | |
} | |
// Method to convert a double to a char array | |
public static char[] numberToByteArray(double number) { | |
// Convert the integer part | |
int intValue = (int) number; | |
char[] intPart = numberToByteArray(intValue); | |
// Convert the fractional part | |
number -= intValue; | |
StringBuilder decimalPartBuilder = new StringBuilder(); | |
decimalPartBuilder.append('.'); | |
int numDecimals = 0; | |
while (number > 0 && numDecimals < 6) { | |
number *= 10; | |
int digit = (int) number; | |
decimalPartBuilder.append((char)('0' + digit)); | |
number -= digit; | |
numDecimals++; | |
} | |
// Remove trailing zeros | |
while (decimalPartBuilder.length() > 1 && decimalPartBuilder.charAt(decimalPartBuilder.length() - 1) == '0') { | |
decimalPartBuilder.deleteCharAt(decimalPartBuilder.length() - 1); | |
} | |
// Concatenate the integer and decimal parts | |
String decimalPartString = decimalPartBuilder.toString(); | |
char[] result = new char[intPart.length + decimalPartString.length()]; | |
System.arraycopy(intPart, 0, result, 0, intPart.length); | |
decimalPartString.getChars(0, decimalPartString.length(), result, intPart.length); | |
return result; | |
} | |
// Method to calculate the number of digits in an integer | |
private static int getNumDigits(int number) { | |
if (number == 0) return 1; | |
int count = 0; | |
while (number != 0) { | |
number /= 10; | |
count++; | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment