Compare 2 Binary Numbers

Hi all ,
suppose I have two arbitrary lenght binary numbers (could be very large binaries).
exple : 1000111 & 11111110001
is it possible to compare them using only there 0s & 1s representations.
i.e I don't want to convert them to base 10 & compare them (probably using BigInteger).
what I'm looking for is an algorithm that compares 1000111 & 11111110001 only using there 0s & 1s sequences.
If this is possible how can I implement it ?
many thanks.

boolean equal = true;
for(inti = ar1.length, j=ar2.lenght; i >= 0 && j
=
0; i--, j--) {
if(ar1[ i ]!=ar2[j]) {
equal = false;
break;
} this code will tell you if ar1 & ar2 are equal but
won't tell you if ar1 <ar2 or ar1>ar2
how can we tell ar1 > ar2 for exple ?oh my bad.
well then indeed one would hav to start at the highest bit and embed the "shorter" value with 0's.
if the representation is in a primitive, eg. long, you cant simply write a < b since java doesnt know unsigned numbers. so either you are carefull enough and only store 31 bits in an int(like leave the highest bit alone) or you check the highest bit first, and then check the remaining.

Similar Messages

  • Operations on very large binary numbers

    Hi guys,
    I'm trying to write a java class for manipulations of very large binary numbers.
    I'm representing the BN internally as boolean[] (array of booleans false for 0 & true for 1).
    I want to write an algorithm for the following operations :
    shifLeft (boolean[] b,int n) : shifting binary number to left by n positions.preferably a circular shift .
    and also the corresponding shiftRight() method.
    can some one guide me on how to implement this ?
    thanks.

    Consider an array of ascii chars....
    array =>   | |a|b|c|d|
    offset = 1
    len = 4In the above there are actually five spots in the
    array but the offset points to the second position in
    the array and the length is 4.
    If I was to extract the value it would be "abcd"
    because of the offset and the length.
    Now a 'shift right' means that if it is "abcd" then
    it should now be "abc" (because the d fell off the
    end.)
    I can do that like this.
    array =>   | |a|b|c|d|
    offset = 1
    len = 3Notice in the above that nothing changed except the
    length. But because the length changed if I
    extracted the value I would get "abc" because the
    offset is 1 and the length is three.
    Notice also that there was no array copying.Are you sure shifting works like that ?
    what I know about left shifting is that the 'd' should be moved left -toghether with a, b, c- and we append a 0 in place of 'd' .
    from what you said the 'd' would be gone , or am I again wrong ?
    it seems i still didn't get any satisfactory answer to this problem...

  • Adding binary numbers in java please help!!

    Hello all, im a total newbie to java and i need your help urgently, i have two variables
    that are integers, that store binary numbers i.e.
    int tmpIntOne, tmpIntTwo;
    tmpIntOne = 1010;
    tmpIntTwo = 1110;
    i want to add these numbers together and return a binary result so far when you add them together you get:
    2120
    however i would like a binary result so that
    result = tmpIntOne + tmpIntTwo;
    = 11000
    Thank you.

    Hello all, im a total newbie to java and i need your
    help urgently, i have two variables
    that are integers, that store binary numbers i.e.
    int tmpIntOne, tmpIntTwo;
    tmpIntOne = 1010;
    tmpIntTwo = 1110;These are not binary numbers. These are decimal numbers whose digits consist of ones and zeros. If you want to interpret the characters "010" as a binary number, then do
    int tmp1 = Integer.parseInt("1010", 2);
    etc.
    i want to add these numbers together
    int result = tmp1 + tmp;
    and return a
    binary result Adding two ints will give an int. Int's are always binary. If you want to display it as a binary String, as opposed to the usual decimal String, then, as suggested, use toBinaryString.

  • Binary numbers to decimal numbers

    Hello, Im writing a program that changes binary numbers to decimal numbers. I seem to be having a probelm calculating the last number in the binary code and adding it to the total. Also, when I use large binary numbers the output isnt anywhere near correct. help? please? thank you

    public class binarynumbers
    public static void main (String [] args)
    int decimal=0;
    Scanner scan= new Scanner(System.in);
    System.out.print("enter binary number> ");
    String bin=scan.next();
    int zero=0;
    int one=1;
    int length=bin.length();
    int newlen=length-1;
    while (newlen>=0)
         String number = bin.substring( zero , one );
         int number1=Integer.parseInt(number);
         int squareRoot=Math.pow(2,newlen);
         decimal+=(squareRoot*number1);
         newlen--;
         zero++;
         one++;
    System.out.println("The decimal number translation is " + decimal);
    i did that but the math part isnt working and im getting a message like this
    binarynumbers.java:26: possible loss of precision
    found : double
    required: int
         int squareRoot=Math.pow(2,newlen);
    ^
    1 error

  • Recursion with binary numbers

    I need to print out a list of all possiblle binary numbers with as many digits as an int k. For example, if k = 3, it would need to print out 000,001,010,011,100,101,110,111. for k = 2 it is only 00, 01, 10, 11. It is pretty clear that for any k, a recursive technique can be used to solve this problem, but I'm having trouble finding the solution. Please help. Thanks

    You don't need recursion:for (int i = 0, max = 1 << (k - 1); i < max; ++i) {
      print binary i to k digits
    }But a recursive approach would be void increment (int[] data, int digit) {
    if (digit > 0) {
    --digit;
    for (int i = 0; i < 2; ++i) {
      data[digit] = i;
      increment(data, digit);
    } else {
    print contents of data array
    start (int k) { increment(new int[k], k); }Neither code tested.
    Pete

  • Comparing two numbers with different formats

    Dear Java developers
    I am trying to compare two numbers but they have different formats. long x = 8981261369, Object obj = "8,981,261,369".
    I am trying to see if this two values are equal which is the case in the example above except one has a thousand separator but not sure how to do that.
    How can I lose the thousand separator and just compare them as two long values.
    Your input will be much appreciated
    Thanks

    iu433 wrote:
    I need a generic way of doing this. Because sometimes the Object does not have a thousand separator. Can i use some kind of NumberFormat to do this.You'll need to know what formats the string (not the number--as already mentioned, numbers don't have formats) can have, and then try them one by one.
    Of course, there can be some ambiguity. Does "123,456" represent one hundred twenty three thousand four hundred fifty six, or is that comma a decimal separator, and it represents one hundred twenty three and four hundred fifty six thousandths?
    The point is, you have to have a clear definition of what formats are allowed and how to determine which one it is. There's no magic way for Java to do that for you.

  • Printing Binary Numbers in SP

    I am trying to print binary numbers in my output.
    Below is the expected output
    1 0x5F6AB40860296D4DB07C346FA12E25FD
    2 0x5F6AB40860296D4DB07C346FA12E25FD
    Below is the output i am getting
    -1590811137
    CREATE
    TABLE Testbinary(
    [ID] [int]
    NOT
    NULL,
    [yVolumeUnitID] [binary]
    (16)
    NOT
    NULL
    insert
    into Testbinary
    values(1,0x5F6AB40860296D4DB07C346FA12E25FD)
    insert
    into Testbinary
    values(2,0x5F6AB40860296D4DB07C346FA12E25FD)
    select
    from Testbinary
    delete Testbinary
    select yVolumeUnitID
    from dbo.MdPriceDesc
    alter
    proc vol
    as
    declare
    @ID
    int,
    @VolumeID
    binary(16),
    @out
    varchar(100)
    begin
    select @ID=ID,
    @VolumeID=yVolumeUnitID
    from Testbinary
    set
    @out = @ID+''+@VolumeID
    print
    (@out)
    end
    exec vol

    You have some implicit conversion going on. Your INT column is ADDED to your VARBINARY column by 
    @out = @ID+''+@VolumeID
    DECLARE @table TABLE (id INT, number VARBINARY(MAX))
    INSERT INTO @table (id, number) VALUES
    (1, 0x5F6AB40860296D4DB07C346FA12E25FD),
    (2, 0x5F6AB40860296D4DB07C346FA12E25FD)
    declare @vb VARBINARY(MAX), @int INT
    SELECT @vb = number, @int = id
    FROM @table
    PRINT @vb
    PRINT @int+@vb
    PRINT CAST(@int AS NVARCHAR)+''+master.sys.fn_varbintohexstr(@vb)
    Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.

  • Compare binary file

    Hi,
    I am using LV 8.5.1. Would like to know, is there any method can compare 2 binary files? Same function as command prompt below:
    fc /b "file 1 path" "file 2 path"
    First do not consider use the system exec.vi.
    Appreciate your feedback.
    Thanks.
    Solved!
    Go to Solution.

    Doing it in LabVIEW is fraught with all sorts of issues that the fc command has probably already addressed.  But if you want to do it, I would recommend the following:
    Read your file in 65,000 byte chunks to optimize disk I/O.
    Compare each chunk.  Your compare operation is up to you.  Note that depending on how you want to compare, you may want to do this byte by byte or chunk by chunk to find the locations of differences, but also find locations which equal, even if they have different offsets (e.g. a difference is a single byte inserted into the file).
    Output your results.  The output is also up to you.  It could be a file, a front panel indicator, the operating system error buffer, etc.
    All in all, this is a lot of work vs. just using the fc command.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Comparing Binary between languages

    Hi,
    if one were to serialize the same object to binary in multiple languages, would one expect that the resulting Binary byte stream and length would be the same in all languages?
    for example:
    MyKey original = new MyKey(414041167, 3, "R");
    SimplePofContext pofContext = new SimplePofContext();
    pofContext.registerUserType(1003, MyKey.class, new MyKeySerializer());
    Binary binary = ExternalizableHelper.toBinary(original, pofContext);
    can I then compare the results from binary.length() and binary.ToByteArray() to those from dotnet and C++ for the same object?
    thanks

    HI JK,
    Thanks, that's what I thought, just that a problem I am having has made me question what I previously thought. For a simple object with three fields I see different binary representations.
    where :
    MyKey = new MyKey(414041167, 3, "")
    I get the following representations
    dotnet:
    {Binary(length=15, value=0xAB0F0000418F91EE8A03016C026240)}
    java:
    Binary(length=17, value=0x15AB0F0000418F91EE8A03016C024E0040)
    The MyKey Class is a simple object with two int members and one string member.
    dotnet serializer:
    class MyKeySerialiser : IPofSerializer
    #region IPofSerializer Members
    public object Deserialize(IPofReader reader)
    var key = new MyKey(reader.ReadInt32(0), reader.ReadInt32(1), reader.ReadString(2));
    reader.ReadRemainder();
    return key;
    public void Serialize(IPofWriter writer, object o)
    var key = (MyKey)o;
    writer.VersionId = 0;
    writer.WriteInt32(0, key.int1);
    writer.WriteInt32(1, key.int2);
    writer.WriteString(2, key.string);
    writer.WriteRemainder(null);
    #endregion
    java serializer:
    public class MyKeySerializer implements PofSerializer {
         @Override
         public Object deserialize(PofReader in) throws IOException {
              in.getVersionId();
              MyKey key =
                   new MyKey(in.readInt(0),
                                       in.readInt(1),
                                       in.readString(2));
              in.readRemainder();
              return key;
         @Override
         public void serialize(PofWriter out, Object oKey) throws IOException {
              MyKey key = (MyKey) oKey;
              out.setVersionId (0);
              out.writeInt (0, key.getInt1());
              out.writeInt (1, key.getInt2());
              out.writeString     (2, key.getString());
              out.writeRemainder(null);
    I believe something strange is happening with the empty string as when I use a key that has the string member variable populated then the binary matches exactly.
    MyKey(683242439, 9, "R"); // works fine
    Any ideas what is going on?

  • How can I add three binary numbers and then convert to string (Hex format)?

    Hi All,
    I have my problem "half" resolved, but need some assistance on the final piece.  Overall, I need to take three string values (hex format), convert them to binary, add them and then convert back to a string (hex format).  If that doesn't make sense maybe this will:
    Final Result (My target) = 0xCC
     = 0x03 + 0x01 + 0x04
              = 0x03; 0011b
              = 0x01; 0001b
              = 0x04; 0100b
    For my app, we are dropping "masking" some of the bits so that we get 1 byte:
              = 0x03; 11b
              = 0x01; 001b
              = 0x04; 100b
    So...
    11001100b = 0xCC
    In my VI, I am taking each initial string [0x03,0x01 and 0x04] type casting them to U8.  Next I need to "mask" the binary values as shown above and then add them.  I am not sure how to do this in LV??
    Thanks for the help,
    Bryan

    Hi Bryan,
    there's a conversion palette in the string palette, ever looked at those functions?
    The rest is pure simple math:
    It's the straight-forward way, there are other possibilities too!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Compare 2 numbers with different precision

    Hi all,
    Using DB 10.2.0.5, I've encountered a strange behaviour today while trying to compare ORA_ROWSCN with a previous SCN sored in a column.
    SELECT
      h.id HID,
      h.ora_rowscn HSCN,
      o.id OID,
      o.scn OSCN,
      h.ora_rowscn-o.scn DIFF
    FROM
      har@REMOTE h LEFT JOIN other o ON (h.id=o.id)
    WHERE
      h.ORA_ROWSCN > o.scn
    ORDER BY 5 desc ;
           HID       HSCN        OID       OSCN       DIFF
    ...{snip}...
          4213 5093868663       4213 5092916724     951939
    1157 rowsWhile casting o.scn to a number gives me another resultset (this one is correct):
    SELECT
      h.id HID,
      h.ora_rowscn HSCN,
      o.id OID,
      o.scn OSCN,
      h.ora_rowscn-o.scn DIFF
    FROM
      har@REMOTE h LEFT JOIN other o ON (h.id=o.id)
    WHERE
      h.ORA_ROWSCN > to_number(o.scn)
    ORDER BY 5 desc ;
           HID       HSCN        OID       OSCN       DIFF
    ...{snip}...
         70949 5093865558      70949 5093847070      18488
    2114 rowsI got the same result if I use NVL(o.scn,0) rather than TO_NUMBER(o.scn).
    I can't find out why this happens. Obviously, the ">" condition doesn't match when the difference is too small.
    AFAIK, ora_rowscn is a NUMBER while my "scn" column is a NUMBER(12) (which should be sufficient to store my DB or remote DB's SCN).
    Does anyone has an explanation?
    Thanks!

    Thank you, I've marked both of your message Helpful.
    @Solomon, maybe you are right, I'll get a try with Materialized Views.
    About my comparison problem, I think I haven't targeted the right spot. Maybe it is an index+ora_rowscn problem. Here is my execution plan:
    SQL>  SELECT h.id hid, h.ora_rowscn hscn, o.id oid, o.scn oscn, h.ora_rowscn-o.scn diff
    FROM har@REMOTE h, other o
    WHERE
       h.id=o.id(+) AND
       h.ORA_ROWSCN > o.scn
    ORDER BY 5 desc ;
    | Id  | Operation                | Name             | Rows  | Bytes | Cost (%CPU)| Time     | Inst   |IN-OUT|
    |   0 | SELECT STATEMENT         |                  |   683 | 17075 |    94   (4)| 00:00:02 |        |      |
    |   1 |  SORT ORDER BY           |                  |   683 | 17075 |    94   (4)| 00:00:02 |        |      |
    |*  2 |   HASH JOIN              |                  |   683 | 17075 |    93   (3)| 00:00:02 |        |      |
    |   3 |    REMOTE                | HAR              | 13658 |   173K|    46   (0)| 00:00:01 | REMOTE | R->S |
    |   4 |    VIEW                  | index$_join$_002 | 14024 |   164K|    46   (3)| 00:00:01 |        |      |
    |*  5 |     HASH JOIN            |                  |       |       |            |          |        |      |
    |*  6 |      INDEX RANGE SCAN    | IDX_OTHER_SCN    | 14024 |   164K|     3  (34)| 00:00:01 |        |      |
    |   7 |      INDEX FAST FULL SCAN| SYS_C006381      | 14024 |   164K|    54   (0)| 00:00:01 |        |      |
    Predicate Information (identified by operation id):
       2 - access("H"."ID"="O"."ID")
           filter("O"."SCN"<"H"."ORA_ROWSCN")
       5 - access(ROWID=ROWID)
       6 - access("O"."SCN"<"H"."ORA_ROWSCN")
    Remote SQL Information (identified by operation id):
       3 - SELECT "ID","ORA_ROWSCN" FROM "HAR" "H" (accessing 'REMOTE' )Where SYS_C006381 is an index on OTHER.ID and IDX_OTHER_SCN is an index on OTHER.SCN column.
    As soon as I drop the latter index, I get the correct resultset:
    SQL> drop index IDX_OTHER_SCN ;
    | Id  | Operation           | Name     | Rows  | Bytes | Cost (%CPU)| Time     | Inst   |IN-OUT|
    |   0 | SELECT STATEMENT    |          |   683 | 17075 |   117   (3)| 00:00:02 |        |      |
    |   1 |  SORT ORDER BY      |          |   683 | 17075 |   117   (3)| 00:00:02 |        |      |
    |*  2 |   HASH JOIN         |          |   683 | 17075 |   116   (2)| 00:00:02 |        |      |
    |   3 |    REMOTE           | HAR      | 13658 |   173K|    46   (0)| 00:00:01 | REMOTE | R->S |
    |   4 |    TABLE ACCESS FULL| OTHER    | 14024 |   164K|    69   (2)| 00:00:01 |        |      |
    Predicate Information (identified by operation id):
       2 - access("H"."ID"="O"."ID")
           filter("O"."SCN"<"H"."ORA_ROWSCN")
    Remote SQL Information (identified by operation id):
       3 - SELECT "ID","ORA_ROWSCN" FROM "HAR" "H" (accessing 'REMOTE' )Well, I can't figure out what's wrong, but the solution is here. Maybe a limitation of ORA_ROWSCN pseudocolumn...

  • Need help with binary numbers

    hey i'm doing some things, but i need a entry of a binary coded number, i know that an hex number is written like 0xFF but how do i put a binary number in an instruction such as:
    byte b
    b="binary number"

    I see what you want to do, but you can only do this with octal and hex. With binary, you would have to do it something like this:
    byte b = Byte.parseByte("01101001", 2); // base-2

  • Strings of binary numbers to integers

    Im quite new to java and have been working on a data compression project as a student. I have two questions:
    Is there an easy way to request the number of bits a particular number will take up without any leading zero's. e.g. 7 = 3 bits
    Is there an easy way to convert a number stored in it's binary form as a string to its decimal equivalent.
    I currently have my own procedures to perform these functions but they require lots of string ops and I am looking to improve performance.
    Any help is appreciated.

    Im quite new to java and have been working on a data
    compression project as a student. I have two
    questions:http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html
    Is there an easy way to request the number of bits a
    particular number will take up without any leading
    zero's. e.g. 7 = 3 bits
    int numBits(int myInt)
       int bits = 32;
       for(int xor = (1 << 31) ; (xor & myInt) == 0 ; xor >>>= 1, bits--);
       return bits;
    Is there an easy way to convert a number stored in
    it's binary form as a string to its decimal
    equivalent.If you mean convert a binary String to decimal,
    String decimalString = Integer.toString(Integer.parseInt(binaryString));

  • Printing hexadecimal/binary numbers

    I'm trying to print the hexadecimal and binary representation of the following:
    public static void main(String[] args) {
    int t = 0x1;
    t = t<<30;
    System.out.println(0xt);
    I tried to print the hexadecimal representation of t using the above, but it didn't work (I know t isn't a hex number, but I want the contents of variable t printed in hex). How can I accomplish this?
    Thanks ahead.

    Use the Integer class. It has methods for binary and hex:
    Integer.toBinaryString(int i);
    Integer.toHexString(int i);

  • Playing with binary numbers

    Hi
    I am messing around with classes. I have a card class, which has a rank (2 - 14) and suit (0-3). What I am trying to do, is have a variable in the class cardvalue which holds a binary value for each card, for example, the 2 (2) of hearts (0) would be 0010 00 (I will of course drop the space), I would like it formatted with the first four digits representing the rank, a the second two the suit, for simple comparison with other cards later on in the game.
    How do I take the card values and concatenate them together?
    Many thanks, Ron

    Thanks, I have this:
    [code
    public class Card
         public enum Rank
         Deuce(2),Three(3),Four(4),Five(5),Six(6),Seven(7), Eight(8), Nine(9), Ten(10), Jack(11), Queen(12), King(13), Ace(14);     
              private final Integer facevalue;
         Rank(Integer facevalue)
         this.facevalue = facevalue;
         public Integer facevalue(){ return facevalue; };
         public enum Suit
              Hearts (0), Clubs(1), Diamonds(2), Spades(3);
              private final Integer suitvalue;
              Suit(Integer suitvalue)
                   this.suitvalue = suitvalue;
              public Integer suitvalue(){ return suitvalue; };
         private final Rank rank;
         private final Suit suit;
         private Integer binaryvalue;//value of the card as a 6 bit number, first two suit, second four rank value
         private Card(Rank rank, Suit suit)
    this.rank = rank;
    this.suit = suit;
    //binaryvalue = rank.facevalue & suit.suitvalue;
    //binaryvalue = Integer(Integer.toBinaryString( rank.facevalue));
         public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public Integer binaryvalue(){ return binaryvalue; }
    public String toString() { return rank + " of " + suit; }
    ]

Maybe you are looking for