Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare int to character constant in Java

I have a binary file that uses sets of 4 chars to form integers that have "meaning". For example, the 4 bytes '0005', which equals 808464437 in integer form.

I'd rather represent these in my Java code as '0005' rather than 808464437. I also don't want to set constants like final int V0005 = 808464437.

In C++, I can do the following:

fileStream->read((byte*) &version, 4); //Get the next bytes and stuff them into the uint32 version

switch (version) {
    case '0005':
        //do something
    case '0006':
        //do something
    case '0007':
        //do something
}

In Java, my problem isn't reading the 4 bytes and putting them into some data type. My problem is comparing some data type to the const char array '0005'.

How do I compare an int, or whatever form, to a const character array like '0005' in Java? I need to do this as efficiently as possible!

like image 964
crush Avatar asked Feb 22 '13 19:02

crush


People also ask

Can you compare char and int in Java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

Can we compare int and char?

Every character got assigned a unique ascii value (ranges from 0-255), any comparison of character with designated ascii value(which is integer) will give you true result. so if i compare ('a'==97) it will be true like. Ans: It's equal.

Can you use == to compare characters in Java?

Using ==, <, > operators you should be able to compare two characters just like you compare two integers. Note: Comparing char primitive values using < , > or == operators returns a boolean value.

Can I use == to compare char?

The char type is a primitive, like int, so we use == and != to compare chars.


2 Answers

Thanks for explaining your answer.

Here's how to convert from 4 bytes to an int, which you can then compare to the int in question:

    int v0005 = ByteBuffer.wrap("0005".getBytes()).asIntBuffer().get();

This is unfortunately the only way I can see to do it... probably not as efficient as you want, but perhaps it's what you need nonetheless.

I would suggest setting up some of these as 'constants' in one of your classes like so:

public static final int V0005 = ByteBuffer.wrap("0005".getBytes()).asIntBuffer().get();
public static final int V0006 = ByteBuffer.wrap("0006".getBytes()).asIntBuffer().get();
public static final int V0007 = ByteBuffer.wrap("0007".getBytes()).asIntBuffer().get();
public static final int V0008 = ByteBuffer.wrap("0008".getBytes()).asIntBuffer().get();

And then switch on V0005, etc, since switching on a primitive type (int) is efficient.

like image 148
vikingsteve Avatar answered Sep 24 '22 05:09

vikingsteve


A char array in java is nothing more than a String in java. You can use string in switch-cases in Java7, but I don't know the efficiency of the comparisions.

Because only the last element of you char array seems to have a meaning, you could do a switch case with it. Something like

private static final int VERSION_INDEX = 3;

...
    char[] version = // get it somehow

    switch (version[VERSION_INDEX]) {
         case '5': 
            break;
         // etc
    }
...

EDIT More object oriented version.

  public interface Command {
       void execute();
  }

  public class Version {
       private final Integer versionRepresentation;

       private Version (Integer versionRep) {
            this.versionRepresentation = versionRep;
       }

       public static Version get(char[] version) {
            return new Version(Integer.valueOf(new String(version, "US-ASCII")));
       }

       @Override
       public int hashCode() {
            return this.versionRepresentation.hashCode();
       }
       @Override
       public boolean equals(Object obj) {
            if (obj instanceof Version) {
                Version that = (Version) obj;

                return that.versionRepresentation.equals(this.versionRepresentation);
            }
            return false;
       }
  }

  public class VersionOrientedCommandSet {
       private final Command EMPTY_COMMAND = new Command() { public void execute() {}};
       private final Map<Version, Command> versionOrientedCommands;

       private class VersionOrientedCommandSet() {
           this.versionOrientedCommands = new HashMap<Version, Command>();
       }

       public void add(Version version, Command  command) {
           this.versionOrientedCommands.put(version, command);
       }

       public void execute(Version version) throw CommandNotFoundException {
           Command command = this.versionOrientedCommands.get(version);

           if (command != null)  {
               command.execute();
           } else {
               throw new CommandNotFoundException("No command registered for version " + version);
           }

       }
  }

  // register you commands to VersionOrientedCommandSet
  char[] versionChar = // got it from somewhere
  Version version = Version.get(versionChar);
  versionOrientedCommandSet.execute(version);

lots of code hehe You will have a little cost of warm-up, but if you program is executed multiple times, you will gain efficiency with the map :P

like image 40
Caesar Ralf Avatar answered Sep 23 '22 05:09

Caesar Ralf