Converting/packing a string of 01010101 to a byte

Hi everyone,
-I need to create a function that will take a string of 1's and 0's.
-The string length will be from 1 to 8, if the length of the string is below 8, it will add trailing 0's (to make 8 bits)
ie. packStrToByte("1011") would return 176 (10110000)
I want to pack that string in a byte so I can write it to an BufferedOuputStream with the method write(int b), where b is a byte.
Example of idea:
packStrToByte("00110001") would return a byte value of 49
ous.write(packStrToByte("00110001") ) would write 1 byte with value 49
I hope i made myself clear!, I really struggle with bit packing....and on top of that i start with a string(which I cannot really implement otherwise)!
Thanks
Patrick Picard

String s = ...;
int val = 0;
for (int i = 0; i < s.length(); i++) {
     int j = (s.length() - 1) - i;
     if (s.charAt(i) == '1') {
            val += (int) Math.pow(2, j);
}Then just cast val to a byte.
However, if you are using Strings to represent bits, chances are something isn't quite right.

Similar Messages

  • Problem with JTree converting Node to string

    I have a problem that I cannot slove with JTree. I have a DefaultMutalbeTreeNode and I need its parent and convert to string. I can get its parent OK but cannot convert it to string.
    thisnode.getParent().toString() won't work and gives an exception
    thisnode.getParent() works but how do I convert this to string to be used by a database.
    Thanks
    Peter Loo

    You are using the wrong method to convert it to a String array.
    Try replacing this line:
    String[] tabStr = (String[])strList.toArray();
    With this line:
    String[] tabStr = (String[])strList.toArray( new String[ 0 ] );
    That should work for you.

  • Is there an easy way to convert a long string into an array?

    I can convert a long string into a 1-d array by parsing and using build array, but I would like to know if there is a function to make this easier.
    For example:
    from/   aaaaaaaabbbbbbbbccccccccdddddddd         (string of ascii)
    to/       an array that is 1-d with each element having eight characters
              aaaaaaaa
              bbbbbbbb
              cccccccc
              dddddddd
    Thank you.
    Solved!
    Go to Solution.

    Try something like this:
    (If you can guarantee that the string length is an integer multiple of 8, you an drop the two triangular modes in the upper left. )
    Message Edited by altenbach on 03-14-2010 06:40 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ChopString.png ‏9 KB

  • Need a function module to convert xstring to string in web dynpro applicati

    hi,
       need a function module to convert xstring to string in web dynpro application other than HR_KR_XSTRING_TO_STRING.
    Moderator message: please (re)search yourself first.
    Edited by: Thomas Zloch on Nov 17, 2010 5:31 PM

    Hi,
    Check the following link:
    FM to convert XString to String
    Regards,
    Bhaskar

  • Converting Datetime in String in map

    Hello all,
    I am reciving a message from a system A, in which I am receiving field DOB as datetime and I am sending same message to system B , problem is that system B not able to handle DOB at there end as datetime - I have checked at BizTalk side that DOB
    is going correct so issue is at system B side. now system B wants BizTalk system to send them DOB field as string.
    What could be the possible way's to do this ?
    1) We can change both schema System A schema and System B schema and map them is one way .
    2) Can we take datetime and convert it to string using some funtoid ? and send that string to system B ? How ?
    Is there other way for this ?
    Thanks,
    Nitin
    Thanks and Regards, Nitin.

    Hi Nitin,
    First find out how the destination system consumes the datatime value. Some system would consume the value in the datetime field as string. It could be the problem in the format of the datetime. Ask them about their expected datetime format. For example
    "2004-09-23T10:20:00.000-05:00" is the standard datetime format produced when you set a field as xssd:datetime. May be the destination system not able to handle this format.
    If the issue is in the datatype i.e. in the way client consume, the datatype of the destination schema matter:
    Then update the destination schema's to have string datetype. And simply map the value from the soruce's datetime field to destination schema's update string field. You don't need any scripting fuctiond to convert the data type. BizTalk's mapper would handle
    it.
    If the issue is in the date format  i.e. in the way client consume, the datatype of the destination schema doesn't matter, and if the actual problem is in the format:
    Then update the destination schema's to have string datetype. Use a scripting fuctiond as suggested by others and do the conversion in the script.
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Help with Sample on Converting an XML string to a byte stream

    Hello All,<br /><br />I am sure this is something simple, but I am just not figuring it out right now.<br /><br />I am following the sample - "Converting an XML string to a byte stream" from the developer guide since I want to prepopulate just 1 field in my PDF form.<br /><br />How do I reference my form field within my servlet code properly??<br /><br />I have tried a few things now, my field is within a subform, so I thought it would be <root><subformName><fieldname>My data</fieldname></subformName></root>  I have also tried adding <page1> in there too.<br /><br />I am following everything else exactly as given in the sample code.<br /><br />I do have an embedded schema within the form and the field is bound.<br /><br />Thanks,<br />Jennifer

    Well, if you have a schema defined in the form, then the hierarchy of your data must match what is described in the schema. So, can't really tell you what it would look like, but just follow your schema.
    Chris
    Adobe Enterprise Developer Support

  • CIN: Converting a C String to a LabVIEW String

    Hi all,
    I have been developing CINs in Microsoft Visual C++ 6.0 for LabVIEW as
    project needs. However, I am having a problem with converting a C String
    to a LabVIEW String in CIN.
    I used two ways to try to make the conversion work that were LStrPrintf
    and MoveBlock as stated as following:
    1. LStrPrintf
    #include "extcode.h"
    #include "hosttype.h"
    #include "windows.h"
    struct teststrct{
    const char* test;
    struct teststrct testinstance;
    typedef struct {
    LStrHandle test
    } TD1;
    CIN MgErr CINRun(TD1 *testcluster, LVBoolean *Error) {
    char *tempCStr = NULL;
    strcpy(tempCStr, testinstance.test); // this would cause LabVIEW crash!
    LStrPrintf(testcluster->test, (CStr) "%s", tempCSt
    r);
    // but if I assigned tempCStr as tempCStr = "test", the string value
    "test" could be passed to LabVIEW without any problems.
    2. MoveBlock
    #include "extcode.h"
    #include "hosttype.h"
    #include "windows.h"
    struct teststrct{
    const char* test;
    struct teststrct testinstance;
    typedef struct {
    LStrHandle test
    } TD1;
    CIN MgErr CINRun(TD1 *testcluster, LVBoolean *Error) {
    char *tempCStr = NULL;
    int32 len;
    tempCStr = (char *)&testinstance.test; //since strcpy didn't work, I
    used this way to try to copy the const char* to char*.
    len = StrLen(tempCStr);
    if (err = NumericArrayResize(uB, 1L, (UHandle*)&testcluster->test,
    len))
    *Error = LVFALSE;
    goto out;
    MoveBlock(&tempCStr, LStrBuf(*testcluster->test), len); // the string
    was able to passed to LabVIEE, but it was unreadable.
    out:
    Did I do anything wrong? Any thougths or suggestions would be very
    appreciated!

    Thank you so much for your response, Greg. However, I still have problem after making
    corresponding modification for LStrPrintf approach:
    int32 len;
    char tempCStr[255] = "";
    strcpy(temCStr, testinstance.test);
    len = StrLen(tempCStr);
    LStrPrintf(testcluster->test, (CStr) "%s", tempCStr);
    LStrLen(*testcluster->test) = len;
    LabVIEW crashes. Any ideas?
    Greg McKaskle wrote:
    > The LStrPrintf example works correctly with the "test" string literal because
    > tempCStr= "test"; assigns the pointer tempCStr to point to the buffer containing
    > "text". Calling strcpy to move any string to tempStr will cause
    > problems because it is copying the string to an uninitialized pointer,
    > not to a string buffer. There isn't anything wrong with the LStrPrintf
    > call, the damage is already done.
    >
    > In the moveblock case, the code:
    > tempCStr = (char *)&testinstance.test; //since strcpy didn't work, I
    > used this way to try to copy the const char* to char*.
    >
    > doesn't copy the buffer, it just changes a pointer, tempCStr to point to
    > the testinstance string buffer. This is not completely necessary, but
    > does no harm and is very different from a call to strcpy.
    >
    > I believe the reason that LV cannot see the returned string is that the
    > string size hasn't been set.
    > Again, I'm not looking at any documentation, but I believe that you may
    > want to look at LStrLen(*testcluster->test). I think it will be size of
    > the string passed into the CIN, and it should be set to len before returning.
    >
    > Greg McKaskle
    >
    > > struct teststrct{
    > > ...
    > > const char* test;
    > > ...
    > > };
    > >
    > > struct teststrct testinstance;
    > >
    > > typedef struct {
    > > ...
    > > LStrHandle test
    > > ...
    > > } TD1;
    > >
    > > CIN MgErr CINRun(TD1 *testcluster, LVBoolean *Error) {
    > >
    > > char *tempCStr = NULL;
    > >
    > > ...
    > >
    > > strcpy(tempCStr, testinstance.test); // this would cause LabVIEW crash!
    > > LStrPrintf(testcluster->test, (CStr) "%s", tempCStr);
    > > // but if I assigned tempCStr as tempCStr = "test", the string value
    > > "test" could be passed to LabVIEW without any problems.
    > >
    > > ...
    > > }
    > >
    > > 2. MoveBlock
    > >
    > > #include "extcode.h"
    > > #include "hosttype.h"
    > > #include "windows.h"
    > >
    > > struct teststrct{
    > > ...
    > > const char* test;
    > > ...
    > > };
    > >
    > > struct teststrct testinstance;
    > >
    > > typedef struct {
    > > ...
    > > LStrHandle test
    > > ...
    > > } TD1;
    > >
    > > CIN MgErr CINRun(TD1 *testcluster, LVBoolean *Error) {
    > >
    > > char *tempCStr = NULL;
    > > int32 len;
    > > ...
    > >
    > > tempCStr = (char *)&testinstance.test; //since strcpy didn't work, I
    > > used this way to try to copy the const char* to char*.
    > > len = StrLen(tempCStr);
    > >
    > > if (err = NumericArrayResize(uB, 1L, (UHandle*)&testcluster->test,
    > > len))
    > > {
    > > *Error = LVFALSE;
    > > goto out;
    > > }
    > >
    > > MoveBlock(&tempCStr, LStrBuf(*testcluster->test), len); // the string
    > > was able to passed to LabVIEE, but it was unreadable.
    > > ...
    > >
    > > out:
    > > ...
    > >
    > > }
    > >
    > > Did I do anything wrong? Any thougths or suggestions would be very
    > > appreciated!

  • Converting a given string to non-english language

    {color:#0000ff}Hi can anybody help me how to convert an entered string in textfield to french or spanish or to anyother non-english language?{color}

    Hi,
    I don't think you get a language translator package.
    What you can do is store the fraises, words in a database.
    //SQL Code
    CREATE TABLE [Language_Data]
      [ID]    INT NOT NULL IDENTITY PRIMARY KEY,
      [Lang]  VARCHAR(30) NOT NULL,                             //Lang English/French.....
      [Type]  CHAR(1) NOT NULL,                                 //is Fraise or Word
      [Words] VARCHAR(100) NOT NULL                             //Fraise or Word data
    GO
    CREATE TABLE [Translate]
      [ID]       INT NOT NULL IDENTITY PRIMARY KEY,
      [FK_Orig]  INT NOT NULL REFERENCES [Language_Data]([ID]), //ID of the original language
      [FK_Trans] INT NOT NULL REFERENCES [Language_Data]([ID])  //ID's for all known translations
    GO Create Stored procedures to add a new word/fraise to the [Language_Data] table,
    Create a Stored Procedure to add a translation to the [Translate] table
    Please note that to add a translation you will first insert into the [Language_Data] table then
    insert the original's ID and the translation ID to the [Translate] table Also make prevision for backwards translation

  • Converting a binary string to a number...

    Hi guys,
    I'm trying to convert a binary string into a decimal integer. I'm not sure if LabVIEW has a VI that does that. I haven't found one yet. Basically, say I have the string '0101'. I want to convert that to the value '5'. Or say I'm using hex, I want '10101111' to be converted to 'AF'. So that's my dilemma. I'm hoping I'm not going to have to make my own VI. Thanks a lot!
    -Mike

    LabVIEW has exactly what you want even if it can be hard to find it.
    To convert a binary text string like "0101" to a decimal value can easily be done using the Scan Value function found under the String/Number conversion section. If you provide the format %b to it (not mentioned in the manual) you will get the decimal value of your binary string.
    Also, on your front panel you can change the format of your numerical indicators by right clicking on it and selecting Format & Precision. If you have a numerical indicator you can set it do display the numbers in e.g. hexadecimal form.
    However, if you want to convert a number to a hexadecimal text string you can use the Number to Hexadecimal String function also found under the String/Number conversion section.
    I
    attached a simple example, Conversions.vi, that shows how it works. I hope this helps. /Mikael
    Attachments:
    conversions.vi ‏14 KB

  • Is there an easy way to convert from a String with a comma, ie. 1,000.00 to

    Is there an easy way to convert from a String with a comma, ie. 1,000.00 to a float or a double?
    thanks,
    dosteov

    Like DrClap said: DecimalFormat. However, make sure you understand the Locale things, as explained at http://java.sun.com/j2se/1.3/docs/api/java/text/DecimalFormat.html (which refers to NumberFormat as well) and use them explicitly. Like
    public class FormatTest
      public static void main(String args[])
        try
          // see NumberFormat.getInstance()
          DecimalFormat fmt = new DecimalFormat();
          Number num = fmt.parse("1,000.01");
          System.out.println(num.doubleValue());
        catch(ParseException pe)
          System.out.println(pe);
    }most likely seems OK on your system, but may print "1.0" (or even fail) on some non-English platforms!
    When performing calculations, also see http://developer.java.sun.com/developer/JDCTechTips/2001/tt0807.html
    a.

  • Converting double to strings

    I'm having a problem in getting my double to convert to a string, here's my code so far.
         public void calculatePayments()
              double paymentAmount;
              double monthlyInterestRate = (Double.parseDouble(interestBox.getText())/12)/100;
              double amountOfLoan = Double.parseDouble(balanceBox.getText());
              double numberOfPayments = Double.parseDouble(yearsBox.getText()) * 12;
              paymentAmount = (amountOfLoan * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate),numberOfPayments));
              Double.toString(paymentAmount);
              tableBox.append(paymentAmount);
    And here's the error message I get:
    ProgramInterface.java:134: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (double)
              tableBox.append(paymentAmount);
    As always, help is appreciated.

    This line returns a String but has no affect on paymentAmount.
    Double.toString(paymentAmount);To covert the double to String you can save the return in a variable
    String s = Double.toString(paymentAmount);
    tableBox.append(s);or combine them
    tableBox.append(Double.toString(paymentAmount));

  • Converting double to String

    I am looking for a way to convert double to String.
    I think that I have to use wrapper like Double class and use toString(double d), but I am not sure how to do it.
    Since toString() is static method, I do not have to have an instance of the Double class, so I was wondering what's the correct way to do it.
    I need something like this:
    String MyString = new String (String1.concat ( My_doubleNumber.Double.toString() ) );
    Any Suggestions?
    Thanks!!!

    WOW thanks a lot. These are definately better than what I thought of doing originally.
    In case I need to use the wrapper class somewhere else, I am just wondering what would be a proper use of Double and String?

  • Converting LRAW to STRING

    Dear All
    I am trying to convert LRAW to STRING, but all the FMs available are for RAW to STRING.
    Is there any FM that can convert LRAW to RAW keeping in mind that the LRAW field has length about 32000
    <moderator: please use meaningfull subject!>
    Edited by: Jan Stallkamp on Aug 6, 2008 2:39 PM

    Hi Vaibhav
    I had solved this problem with a different work around where I used the ABAP program for sxmb_moni and used its features to get the output.
    Thanks

  • Converting Double to String without exponent

    Hi all,
    I am reading some values from Excelsheet using apache POI library. I have large numbers that need to stored into database as string and not numbers. hence, while reading the excelsheet values, i convert these number.. and the are received as double. While converting double into string I noticed that some values are represented in exponential form.. I would like to avoid this and have pure number values in the form of string,,..
    Can anybody tell me how to do it?
    Thanks in advance,
    Abdel Olakara

    java.text.DecimalFormat

  • Converting from spreadshet string to array and then back to spreadsheet string

    My questions is; why is the Spreadsheet string to array function creating more data than the original string had when you change the array back into a spreadsheet string. Im trying to analyze a comma delimited file using array functions since my column and row size is constant, but my data varies. Thus my reason for not using string parsing functions which would get more involved and difficult. So, however, after i convert to a 2D array of data from the comma delimited file I read from, and then I convert back to string using the Array to Spreadsheet String, I get added columns to the file, which prevents another program from receiving these files. Also, the data which I am reading is not all contiguous, it has gaps in some places for empty data. Looking at the file compared to the original after it has gone from string to array and then back to string again, looks almost identical except for the file size which got larger by 400 bytes and where the original file has empty spaces, the new file has a lot of commas added. Any idea?
    Charles

    The result you get is normal when the spreadsheet string contains rows of uneven length. Since the array rows have the same number of elements, nil values are added during the coonversion. And of course, the back to string conversion keep those added values in the string, with the associated commas.
    example : 3 x 3 array
    1,2,3
    4
    5,6,7
    is converted into
    1 2 3
    4 0 0
    5 6 7
    then back to
    1,2,3
    4,0,0
    5,6,7
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

Maybe you are looking for

  • Cancel 'Local object' status

    Hi Everybody, During installation of DataSource from Business content (RSA5), the status of DataSource was accidentally switched to 'Local Object'. As a result it's not possible to modify the DataSource in Customizing cockpit (LBWE) and replicate it

  • Form Size becoming Too large

    Hello, I have a very strange problem. I designed a fillable form using Designer7.0. I reader enabled the form using Adobe Reader Extensions Server 7.0, so that users use their Adobe reader(7.0.5) to fill in the form. The empty PDF form is around 700K

  • Install 10.6 server on MacBook Pro?

    I run a traveling newsroom and currently run 10.3 server just fine on a G4 Mini for years. Now need to upgrade machines and server software so would like to run on a MacBook Pro. Apple doesn't OFFICIALLY support server on non-desktop macs, but I just

  • Insalation issues

    I am unable to install my Photoshop Elements 9 on my new iMAC because it does not have a cd tray.  What are my options?

  • Connection failed to Oracle Applicatio n Server10g 10.1.3

    Hi, i m using jdeveloper 10314, i m trying to connect oracle application server but after entering all the required parameter when i test the connection it gives me error *"Error while getting remote MBeanServer for url: ormi://apo13090080:12403/defa