Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's my version of a long to packed decimal method.</p> <pre><code>public class PackedDecimal { public static byte[] format(long number, int bytes) { byte[] b = new byte[bytes]; final byte minusSign = 0x0D; // Minus final byte noSign = 0x0F; // Unsigned String s = Long.toString(number); int length = s.length(); boolean isNegative = false; if (s.charAt(0) == '-') { isNegative = true; s = s.substring(1); length--; } int extraBytes = length - bytes + 1; if (extraBytes &lt; 0) { // Pad extra byte positions with zero for (int i = 0; i &lt; -extraBytes; i++) { b[i] = 0x00; } } else if (extraBytes &gt; 0) { // Truncate the high order digits of the number to fit s = s.substring(extraBytes); length -= extraBytes; extraBytes = 0; } // Translate the string digits into bytes for (int i = 0; i &lt; length; i++) { String digit = s.substring(i, i + 1); b[i - extraBytes] = Byte.valueOf(digit); } // Add the sign byte if (isNegative) { b[bytes - 1] = minusSign; } else { b[bytes - 1] = noSign; } return b; } public static void main(String[] args) { long number = -456L; byte[] b = PackedDecimal.format(number, 5); System.out.println("Number: " + number + ", packed: " + byteToString(b)); number = 0L; b = PackedDecimal.format(number, 5); System.out.println("Number: " + number + ", packed: " + byteToString(b)); number = 5823L; b = PackedDecimal.format(number, 5); System.out.println("Number: " + number + ", packed: " + byteToString(b)); number = 123456L; b = PackedDecimal.format(number, 5); System.out.println("Number: " + number + ", packed: " + byteToString(b)); } public static String byteToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; b.length; i++) { sb.append("0x"); sb.append(Integer.toHexString((int) b[i]).toUpperCase()); sb.append(" "); } return sb.toString(); } } </code></pre> <p>And here are the test results.</p> <pre><code>Number: -456, packed: 0x0 0x4 0x5 0x6 0xD Number: 0, packed: 0x0 0x0 0x0 0x0 0xF Number: 5823, packed: 0x5 0x8 0x2 0x3 0xF Number: 123456, packed: 0x3 0x4 0x5 0x6 0xF </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload