Getting the base-36 representation of a byte[8]

Hello all.
I am in the process of writing a J2ME client for a properitary protocol transmitting stock data.
Simply put my problem is that I need to get the base-36 (0-9AZ) representation of a 64 bit unsigned number (stored in a byte[8]).
To be more elaborate, I am encrypting a string using the Blowfish algorithm (from www.bouncycastle.org), and the resulting blocks are to be sent to the server as a base36 string representing the block.
Since I am on J2ME I do not have access to Sun's BigInteger, but Bouncycastle provides a lightweight one, however I think it is a bit buggy. Nor do I have access to the J2SE formatter classes.
Ideally I would want to do something like this:
Long.toString( (long)bytearray, 36 );
This of course do not work since
1) Jave does not support casting byte[] to long, this could however be fixed by bitshifting.
2) Long is always signed and I am really at a loss on how to do this.
Any ideas?
Regards Johan Seland

Is your byte array big endian or little endian? I'll assume little endian.
package base36;
import java.util.*;
* <p>Single Sentence Description. </p>
* <p>Long Description. </p>
* <p>Copyright: &copy; 2003</p>
* <p> </p>
* @author Paul Murray
* @version 1.0
public class Main
    public static void main(String[] args) {
        Main main1 = new Main();
        main1.go();
    void go() {
        for (int i = 0; i < 13; i++) {
            System.out.print("36 ^ " + i + " = ");
            for (int j = 0; j < 8; j++) {
                System.out.print(Integer.toHexString((((int)powers[i][j])>>4)&15));
                System.out.print(Integer.toHexString(((int)powers[i][j])&15));
                System.out.print(' ');
            System.out.println(' ');
        byte[] amt;
        amt = new byte[] {0, 0, 0, 0, 0, 0, 0, 0};
        dump(amt); System.out.println(" = " + cvt(amt));
        amt = new byte[] {1, 0, 0, 0, 0, 0, 0, 0};
        dump(amt); System.out.println(" = " + cvt(amt));
        amt = new byte[] {0, 1, 0, 0, 0, 0, 0, 0};
        dump(amt); System.out.println(" = " + cvt(amt));
        amt = new byte[] { -1, -1, 0, 0, 0, 0, 0, 0};
        dump(amt); System.out.println(" = " + cvt(amt));
        amt = new byte[] { 0, 0, 1, 0, 0, 0, 0, 0};
        dump(amt); System.out.println(" = " + cvt(amt));
        amt = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1};
        dump(amt); System.out.println(" = " + cvt(amt));
        amt = new byte[] { -2, -1, -1, -1, -1, -1, -1, -1};
        dump(amt); System.out.println(" = " + cvt(amt));
    void dump(byte[] d) {
        for(int i=0;i<8;i++) {
            System.out.print(Integer.toHexString((((int)d)>>4)&15));
System.out.print(Integer.toHexString(((int)d[i])&15));
System.out.print(' ');
* powers of 36. we use an array of short to nix sign extension. I happen to know that
* there are 13 powers of 36: n < 2^64
static short[][] powers = new short[13][];
static {
// initialise the array of powers of 36
short[] p = new short[] {
1, 0, 0, 0, 0, 0, 0, 0};
int index = 0;
for (; ; ) {
powers[index] = new short[8];
System.arraycopy(p, 0, powers[index], 0, 8);
index++;
int carry = 0;
for (int i = 0; i < 8; i++) {
int mul = p[i] * 36 + carry;
p[i] = (short) (mul & 0xFF);
carry = mul >> 8;
if (carry != 0)
break;
assert index == 13:"there are exactly 13 64-bit powers of 36";
// use a single instance - not thread safe
short working[] = new short[8];
StringBuffer amt = new StringBuffer();
String cvt(byte[] n) {
if (n.length != 8)
throw new IllegalArgumentException("length of 8, please");
amt.setLength(0);
for (int i = 0; i < 8; i++)
working[i] = (short) ( ( (int) n[i]) & 0xFF);
for (int currentPower = 12; currentPower >= 0; currentPower--) {
int digit = 0;
while (lessThanOrEqualToWorking(powers[currentPower])) {
digit++;
subtractFromWorking(powers[currentPower]);
if (digit < 10) {
amt.append((char)('0' + digit));
else {
amt.append((char)('A' + digit - 10));
return amt.toString();
boolean lessThanOrEqualToWorking(short[] p) {
assert p.length == 8;
for (int i = 7; i >= 0; i--) {
if (p[i] > working[i])
return false;
if (p[i] < working[i])
return true;
return true;
void subtractFromWorking(short[] p) {
assert p.length == 8;
boolean carry = false;
for (int i = 0; i < 8; i++) {
if (carry)
working[i]--;
working[i] -= p[i];
if (working[i] < 0) {
working[i] += 256;
carry = true;
else {
carry = false;
assert!carry:"param must be < working";

Similar Messages

  • How to get the size of a string in bytes

    Morning,
    I’m trying to get the length in bytes of a string, the characters below are 3 byte UTF-8, but when I display
    The length of either int, looks like is double I got 120 and I think it should be 60. Any idea
    String requiredMsg = "όόόόόόόόόόόόόόόόόόόό";
    int byteCountUTF8 = requiredMsg.getBytes("UTF-8").length;
    int byteCountUTF8 = requiredMsg.getBytes().length;
    thanks

    OK, it is not 'o with acute', but rather 'Greek small omicron with tonos'.
    This page may help you sort it out:http://www.fileformat.info/info/unicode/char/3cc/index.htm.
    According to the page and to my tests, this Unicode 03CC has a 2 bytes (not 3) UTF-8 representation.
    String requiredMsg = "\u03CC";
    System.out.println(requiredMsg.getBytes("UTF-16").length);
    System.out.println(requiredMsg.getBytes("UTF-8").length);
    System.out.println(requiredMsg.getBytes().length); // In WindowsResult on my machine:
    4
    2
    1

  • How does WebLogic 8.1 get the BASE HREF value?

    We have a WebLogic 8.1 SP4 server with a Juniper DX load balancer in front. We are trying to get Juniper to handle all the SSL traffic for the WebLogic application. Between Juniper and WebLogic, it would be just HTTP and between Juniper and web clients it would be HTTPS. One of the main issues we are seeing is that Struts HTML:BASE tag is returning the Juniper address as we expected, with the correct SSL port and application context/paths. However, the protocol for this base href is set to HTTP and not HTTPS. Consequently, our pages do not load properly.
    I am trying to understand where this value comes from. The underlying code uses request.getScheme() to get the protocol. So, we could "customize" the tags to work around this, but that is a hack that I am trying to avoid. I assume that the HTTP stack that WebLogic 8.1 uses is providing this info from the HTTP request. Does this come from the web browser? How does WebLogic get this to put it into the request object in the web container? We have sniffed the HTTP headers on the web client side and we cannot see where this is coming from.

    I remember facing a similar issue with webloigc 8.1 and apache
    I dont think its a problem with the tag..
    I think i have changed the transport-guarantee in web.xml
    If you have NONE try setting that to CONFIDENTIAL and vice versa

  • Getting the "code" of a class as byte array

    Hi!
    My problem is the following. My algorithm gets a Class object and it should return the code of the class as byte array.
    e.g. public byte [] getTheCode (Class forThisClass);
    I found out, that I can get an InputStream for a ressource, so that i can load my own classes like getResourceAsStream("my/package/MyClass.class"), but it should also be possible to get the code of the built-in classes like String, Integer etc.
    thanks, Ingo

    The real name of String is java.lang.String; perhaps you didn't use the full name.No, that's not the problem. The classloader of java.lang.String is usually the bootstrap class loader, and its Class.getClassLoader() == null.
    Class.getClassLoader() explicitly defers to the system class loader (not the bootstrap class loader) if getClassLoader() == null, The system class loader (the thing that looks at CLASSPATH, etc.) cannot load anything from rt.jar.
    So basically I think you're sort of SOL, unless you want to check for this condition yourself. I.e. first try your approach (using getResourceAsStream()), and if that returns null, go and open ${java.home}/lib/rt.jar, and walk it on your own.

  • How to get the base url

    Hi,
    when configure the BPM, we set the base url (http://host:port/), which will be used in the default notification sent by bpm.
    now we want to include that url in our notification step. is there a way to get that url?
    Best regards,
    John

    Hi John,
    Would you please share the solution you found for this problem, maybe the EJB source codes or something like that? It would really help the ones like me who have the same problem and looking for a solution.
    Thanks in advance...
    Best regards,
    Utku.

  • How to get the best colour representation on screen

    Hi there,
    I am trying to get my LCD to most accurately represent colours from my Pantone swatch book. I have a Huey Pro calibration tool to assist in the LCD calibration.
    So, I've calibrated the display as best as I could. It's not a top of the line LCD and the Huey isn't the top of the line colourimeter so I understand that I won't get things absolutely perfect.
    I'm starting with the basics: trying to match the C M Y & K from the swatch book. Figure that's a good place to begin. I'd like to see RGB and CMYK values look as accurate as possible on my display. If I can figure that out, then I guess it's time to understand how to match the Pantone values and the Lab settings and all that jazz.
    My PS Colour Settings are North America General Purpose 2
    RGB: sRGB IEC61966-2.1
    CMYK: US Web Coated (SWOP) v2
    Is there anything else I can be doing to get a better on-screen representation?
    Is this Holy Grail even attainable with my modest setup?
    I'd really value your advice and opinions!
    Thanks!

    Humm could be one of two things...
    If the Display Resolution is off, go to: Apple > System Preferences > Displays > select the Display tab and choose the highest Scaled Resolution in the list.
    If just the Desktop picture is to narrow, go to: Apple > System Preferences > Desktop & Screen Saver > select the Desktop tab and change the Fit to Screen setting to Fill Screen.
    Likewise, I might complain to Verizon because those folks had no business messing with those setting.

  • Should I get the base model MacBook Pro Retina 13" (2.4ghz/8gb/256gb) or is it worth upgrading the processor to the 2.6ghz

    I'm looking to get a new computer and would like the the retina display. I do a fair amount of video editing and photo editing. I was wondering if the faster processor would make a difference. I was also looking at the refurbished 15" retinas and didn't know if that would be better for me or not.

    If you need photo and video editing, go for the 15-inch MacBook Pro with Retina display. The 13-inch MacBook Pro with Retina display won't work correctly for what you want to use the MacBook for, as it has only got an integrated GPU, and some photo and video editing applications are not compatible with these GPUs.
    Instead, the 15-inch MacBook Pro has got a quad-core processor and two GPUs, one for the general use and another one for tasks that require extra performance, so it will work better. If you don't mind losing performance to save money, go for the 13-inch MacBook Pro, and note that you have 14 days to return the MacBook Pro if it doesn't meet your needs

  • E5 share online...where to get the base install pa...

    I have seen an E5 with share online installed. Mine does not. Can't update what I do not have. Any one have or know where to get ??

    Look here: http://europe.nokia.com/support/learn-how/sharing-and-blogging .  The web site looks a bit out of date, but you should get version 4.3.  (Version 4.3.10.09 came preinstalled on my E73.)
    As I type this, your post is the top entry in the "Latest Discussions" field on the above site.  Hehe.

  • How do i get the file properties of any file in the phone?

    i need to get the meta data / properties of files in the phone.
    in addition, i will need the song title, artist, genre, etc information from video and audio files.
    can somebody help?

    but i cant seem to find any APIs Impl. would definitely complex.. as there are no stright api. matching your exact need (not sure if some third party has any library meeting your needs).
    that support the function of reading the whole file as the WHOLE file (headers + content).You could read byte by byte or set of bytes using read() and its overloaded method and store in byte[] array.
    It get the meaning full understanding of these bytes and get what you really need.. for the audio and video file, you need to go to the specification and read the bytes accordingly.
    if there are, then is there a way to rewrite the file?
    is there a way to change the bits in the file without creating a new one?Yes you could if you open the file with readwrite (look at Connector) mode and with OutputStreamWriter.
    Some of the challenges you would phase are memory issues, performance issues while reading big files..
    Regards,
    Raja Nagendra Kumar

  • How can I get the values on Xaxis and Yaxis?

    Hi, I would like to get the values that are on the axis X and Y or to get the base value and the ticks interval for calculating the values.

    You can get the base values and intervals via the following properties:
    XAxis.MajorDivisions.Base
    XAxis.MajorDivisions.Interval
    XAxis.MinorDivisions.Base
    XAxis.MinorDivisions.Interval
    YAxis.MajorDivisions.Base
    YAxis.MajorDivisions.Interval
    YAxis.MinorDivisions.Base
    YAxis.MinorDivisions.Interval
    Note that calculating the values from these properties will only work if the axis AutoSpacing property is false. Otherwise, the ticks and labels are automatically determined by the graph depending on the available space to present something that always looks nice.
    - Elton

  • Send the Base 64 binary string to printer

    Hi All,
    I get the base 64 binary data in a string from the file and I need to print a image from SAP.
    I am able to decode the data and download the image into a jpeg file .
    What I need is to send this as a print request to a label printer .
    Could you please help me .
    Thanks in advance
    Raj

    [http://forums.sun.com/thread.jspa?threadID=5427379&tstart=0|http://forums.sun.com/thread.jspa?threadID=5427379&tstart=0]
    Double posting buttlicker!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Do you really think that you are the only to discover that there is more than one forum? Post in one place thankyou.

  • How do I get the byte size of a server file before sending output via HTTP?

    I need to get the byte size of the file prior to streaming it. I can't seem to find a class/method I need. Basically, I have the path c:\\tomcat\\webapps\\documents\\sample.pdf in the servlet, I was hoping I could just use something from the File class but I couldn't find anything that seems to do the trick?
    thanks, in advance,
    Chuck

    maybe the source of the problem will help...I am trying to stream a PDF to IE and a blank page is being generated although all other file type work.
    I have found a lot of answers in the forum but no specific code examples. Here's what I have so far from picking through threads in here (can someone please show me how to get the byte size of the file so that I can assign it to the method response.setContentLength();?):
    String CONTENT_TYPE = " ";
         String target = " ";
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
         StringBuffer buf = new StringBuffer();
         HttpSession session = request.getSession();
         String file = request.getParameter("filename");
         target = file;
         int end = file.length();
    int beg = end-2;
         String type = file.substring(beg, end);
         if (type.equals("DOC")){
              CONTENT_TYPE = "application//vnd.msword";
         }else if (type.equals("XLS")){
              CONTENT_TYPE = "application//vnd.x-excel";
         }else if (type.equals("PPT")){
              CONTENT_TYPE = "application//vnd.ms-powerpoint";
         }else if (type.equals("PDF")){
              CONTENT_TYPE = "application//vnd.x-pdf";
         }else if (type.equals("MPP")){
              CONTENT_TYPE = "application//vnd.ms-project";
         }else if (type.equals("ZIP")){
              CONTENT_TYPE = "application//ZIP";
         }else if (type.equals("TXT")){
              CONTENT_TYPE = "text//plain";
         }else {
              CONTENT_TYPE = "text//html";
         //File f = new File(file);
         //int l = f.length();
         response.setContentLength(l); <----- supposedly this fixes my problem but I don't know how to get the byte szie of the file in an integer??
         // reset the response
         response.reset();
         response.setContentType(CONTENT_TYPE);
         try{
         // Get streams
         FileInputStream fileInputStream = new FileInputStream(target);
         ServletOutputStream servletOutputStream = response.getOutputStream();
         // Init byte count and array
         int bytesRead = 0;
         byte byteArray[] = new byte[4096];
         // Read in bytes through file stream, and write out through servlet stream
         while((bytesRead = fileInputStream.read(byteArray)) != -1) {
         servletOutputStream.write(byteArray, 0, bytesRead);
              servletOutputStream.flush();
         // Flush and close streams
         servletOutputStream.flush();
         servletOutputStream.close();
         fileInputStream.close();
         } catch (Exception e) {
         System.out.println(e.toString());

  • How to get the number of bytes stored in a field?

    Hi Guys,
    How can i get the number of bytes stored in a field.
    I tried using DESCRIBE FIELD, But here i am getting the length from the definition.
    i.e 8 bytes for string and for character value is from definition.
    Prompt replies will be Awarded with full points:-)
    Thanks,
    vinod.

    u see this : http://help.sap.com/saphelp_nw04/helpdata/en/cf/21f2e5446011d189700000e8322d00/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21f2e5446011d189700000e8322d00/frameset.htm
    Madhavi

  • How to get the number of bytes at TCP port

    Hi all,
    How to get the number of bytes to read at the TCp port...as someone had suggested in some forum we do read the number of bytes first and then pass this...
    but we get a problem when we have FF data in this...because then it sends 2 FF data...and cause of this we skip the last data...is there any solution for the same?

    Hi
    In LabVIEW you don't have the same property as in serail port.
    You havn't "Byte at TCPIP port".
    if you developp a protocol, one soltion, is to send the size to read.
    Ingénieur d'Application / Développeur LabVIEW Certifié (CLD)
    Application Engineer / LabVIEW Certified Developer (CLD)

  • I want to set up a roaming network. I have directions. I have an extreme set up and working.  I need to add an express.   When I open airport utility I get the internet pic of internet and the base station.  How do a get to the setting screens?

    Directions require that I change settings on the base station on the screen that interent connection, TCP/IP DHCP NAT how do I get to that screen through airport utility.
    Then I need to for my express to get to the screen the screen for wireless.
    This has changed since last time I did this.
    How do I get to the screens.

    Your existing Extreme might already be configured in Bridge Mode. As long as the Extreme is working now, do not change any settings on the Extreme.
    Apple incorrectly assumes that all users are connecting to a simple modem when most users are connecting to gateway devices....combination modem/routers. 
    You probably are as well and Bridge Mode would be the correct setting when connecting to that type of device.

Maybe you are looking for

  • Disk Utility/ OS 10.2.8 problem

    I wanted to use Disk Utility to reformat a boot partition of my external FW drive. The install OS 9 drivers option is greyed out. Is that because the drivers are already on the whole disk? Been so long since I have had to do this I don't remember Tha

  • AirPlay mirroring from Apple devices to Apple TV not working

    Hello, I just bought a Apple TV (3rd gen) the other day. I updated it to the newest firmware, but I still cant use AirPlay. I have a Macbook Pro (mid 2012) on mountain lion, a iPad 2 (ios 6.0.1), and a iTouch 4th gen (6.0.1), but I cant seem to get a

  • How to unzip the BIG entries ...

    Dear sirs/madam: I encounter a great difficult problem in uncompressing a zip file which has the BIG entries excess 4GB. Is there any size limitation in doing uncompress files in Java? Or there is any resolutions? JDK: 1.4.2 OS: Windows XP It will be

  • How do I burn iTunes library onto DVD-RW? I'm a schmuck.

    Tab: Advanced/Burn only says data - CD; Why can't I burn it as a Audio DVD. I checked help. I got Itunes 6, Sonic ain't working. Neither is Windows Media player. I don't get it. I created playlist, went back to main library, selected all, then back t

  • Media Player Volume Control

    The default media player has a volume control that I do not remember how to adjust.  Guidance Sought