java - convert extremely large decimal to bytes -
java - convert extremely large decimal to bytes -
how convert extremely big (>1mb) decimal numbers bytes/hex/binary?
for example, number "300" should converted {0x01, 0x2c}. byte order doesn't matter , {0x2c, 0x01} ok.
the source numbers stored in prepped file (without puntuation, whitespace or linebreaks). largest just on 17mb, although can't rule out i'll have 100mb number in future. destination file.
is there way doesn't take ages, or fail-safe in case does take ages?
i fear using biginteger
take ages , not fail-save (ie. can't resume half-way if goes wrong)
i'm not against implementing own algorithm, although i'm looking more efficient 'check if odd, split 2'. i've seen efficient implementation of binary bcd, shift , add-3 algorithm, , looking efficient implementation in reverse.
an kudos implementation supports fixed-point numbers (with 1 digit , rest decimals, eg. pi).
for me biginteger
converts 1m digits byte []
in ~39 seconds. much you?
random r = new random (); stringbuilder sb = new stringbuilder(); (int = 0; < 1000000; i++) sb.append ("0123456789".charat(r.nextint(10))); long t = system.currenttimemillis(); biginteger bi = new biginteger (sb.tostring()); byte [] bytes = bi.tobytearray(); system.out.println(system.currenttimemillis() - t);
about decimals. lets assume have big decimal in form <n digits>.<m digits>
. want convert binary k
bits after dot. need solve equation: d/(10^m) = x/(2^k)
, x integer. here d decimal without dot (mantissa of decimal), x binary without dot (mantissa of binary). equation easy solve: x ~ round(d*(2^k)/(10^m))
. x has integer, added round()
.
for illustration need convert 12.34 binary 3 bits after dot.
n = 2 m = 2 d = 1234 k = 3 x ~ round(d*(2^k)/(10^m)) = round(1234 * 8 / 100) = round(98.72) = 99 = 1100011b
remember desired 3 bits after dot, our reply 12.34 ~ 1100.011b
all these calculations can done using biginteger.
java binary numbers decimal converter
Comments
Post a Comment