CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Array type

  1. #1
    Join Date
    Sep 2009
    Posts
    20

    Array type

    Hello !!!
    i want to store some binary numbers in an array::
    suppose i have five binary numbers ::
    001,0010,0011,00,0000011;
    so which type of array should i select?
    also how to initialize that array!!
    so that i can retrieve it as binary numbers not the ascii values of 0s and 1s(as in String type).

    please help me!!!

  2. #2
    Join Date
    Feb 2008
    Posts
    966

    Re: Array type

    What have you done to try and help yourself? Have you even tried reading any of the Java docs or Googling? Try doing a little research before asking for the answer, it isn't hard to find.

  3. #3
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Array type

    Everything in a computer is in binary. For example byte, short, int, long are all stored as binary (8 binary bits to a byte).

    What do you want to be stored when you say "binary"?
    Norm

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Array type

    Quote Originally Posted by arpit2309 View Post
    Hello
    The only way you can preserve leading zeroes in numbers is to actually store the numbers as Strings. So I suggest you make it a String array.

    Then when you need to convert from a binary String representation to a decimal number you can use the parseInt method of the Integer class.
    Code:
    String s="0011";
    int n=0;
    try {
       n = Integer.parseInt(s, 2);
    } catch (NumberFormatException e) {
       // conversion error - do something
    }
    A complication here is that parseInt can throw an exception so the call must be made within a try-catch block.

    The 2 in the parseInt call (the radix) means the String should be interpreted as a binary number.

    If you print n after the conversion it should be 3. This is because 11 in binary is 3 in decimal. Note however that if you were to extract the internal binary representation of n you would find it to be 11 as expected.

    If you change the radix to 10, n will be 11. This is because 11 in decimal is 11 in decimal (seems reasonable). The internal binary representation of n however will be 1011.

    If you don't have to preserve leading zeroes of the binary Strings you can convert them to ints and store them in an int array. But how do you get the binary String representation back? Amazingly the Integer class offers a method also for that called toBinaryString.
    Last edited by nuzzle; September 15th, 2010 at 11:06 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured