如何將double轉換爲Java中的字節數組?我看了很多其他帖子,但無法找出正確的方法。將double轉換爲byte []數組
Input = 65.43
byte[] size = 6
precision = 2 (this might change based on input)
expected output (byte[]) = 006543
我可以不使用函數doubleToLongBits()嗎?
如何將double轉換爲Java中的字節數組?我看了很多其他帖子,但無法找出正確的方法。將double轉換爲byte []數組
Input = 65.43
byte[] size = 6
precision = 2 (this might change based on input)
expected output (byte[]) = 006543
我可以不使用函數doubleToLongBits()嗎?
public static byte[] encode(double input, int size, int precision) {
double tempInput = input;
for (int i = 0; i < precision; i++) tempInput *= 10;
int output = (int) tempInput;
String strOut = String.format("%0"+size+"d", output);
return strOut.getBytes();
}
它是完美的,但我還會添加一個參數來指示區域設置以避免出現問題,或者。在輸入的小數部分 – sataniccrow
是的,但不要忘記在不同的功能中完成這項工作。我給你的函數需要一個double作爲輸入,而不是一個字符串...使用'NumberFormat format = NumberFormat.getInstance(Locale.FRANCE))'例如,如果你得到一個逗號而不是一個句點作爲輸入。 (然後使用'format.parse(inputString).doubleValue();')不要忘記檢查這個答案:) – durron597
double doubleValue = 10.42123;
DecimalFormat df = new DecimalFormat("#.##");
String newDouble = df.format(doubleValue);
byte[] byteArray = (newDouble.replace(",", "")).getBytes();
for (byte b : byteArray) {
System.out.println((char)b+"");
}
意大利語區域...因此,作爲十進制符號 – sataniccrow
真正double
到byte[]
轉換
double d = 65.43;
byte[] output = new byte[8];
long lng = Double.doubleToLongBits(d);
for(int i = 0; i < 8; i++) output[i] = (byte)((lng >> ((7 - i) * 8)) & 0xff);
//output in hex would be 40,50,5b,85,1e,b8,51,ec
double
到BCD轉換
double d = 65.43;
byte[b] output = new byte[OUTPUT_LENGTH];
String inputString = Double.toString(d);
inputString = inputString.substring(0, inputString.indexOf(".") + PRECISION);
inputString = inputString.replaceAll(".", "");
if(inputString.length() > OUTPUT_LENGTH) throw new DoubleValueTooLongException();
for(int i = inputString.length() - 1; i >= 0; i--) output[i] = (byte)inputString.charAt(i)
//output in decimal would be 0,0,0,0,6,5,4,3 for PRECISION=2, OUTPUT_LENGTH=8
這是我得到基於你的投入,它符合我的目的。感謝您的幫助!
static int formatDoubleToAscii(double d, int bytesToUse, int minPrecision, byte in[], int startPos) {
int d1 = (int)(d * Math.pow(10, minPrecision));
String t = String.format("%0"+bytesToUse+"d", d1).toString();
System.out.println("d1 = "+ d1 + " t="+ t + " t.length=" + t.length());
for(int i=0 ; i<t.length() ; i++, startPos++) {
System.out.println(t.charAt(i));
in[startPos] = (byte) t.charAt(i);
}
return startPos;
}
您是否嘗試創建二進制編碼的小數?這就是你的輸出結果,但這個問題並不是很清楚。 – lynks
不完全是,我想要移除小數點。如果我輸入9999.1234,我的輸出應該是999912 – swap