Int to char - char to int

I have 2 methods.
The first method takes an int from 0-256 and casts it to a char and then places the char in a string:
cCryptedString [iLoop] = (char) iCryptedValue;
The second method reads the string and casts each character from it into an int.
iPassStringValue = (int) aString.charAt(iLoop);
If the iCryptedValue in the 1st method is > 127 and < 150 (because that's as far as they will go at the moment), the casting of that int (i.e. 145) to a char results in a ? being placed in cCryptedString[iLoop].
When the 2nd method reads the string and encounters the ? placed by the first method, the casting of that char to an int results in a 63 (the ascii value of a ?) instead of the original 145.
This was not a problem until I installed and ran WebLogic 6.0 sp2 using jdk 1.3 on a Windows 2000 machine. It is working fine under WebLogic 5.1 using jdk 1.2.2.
Any ideas?
Thanks,
Mark

Here is the 1st method:
public String encryptString(String aString) {
int iPassStringValue = 0;
int iEncryptKeyValue = 0;
int iCryptedValue = 0;
char cCryptedString [] = new char[aString.length()];
for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
iPassStringValue = (int) aString.charAt(iLoop);
iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
iCryptedValue = iPassStringValue + iEncryptKeyValue;
if (iCryptedValue > 255)
iCryptedValue = iCryptedValue - 256;
cCryptedString [iLoop] = (char) iCryptedValue;
return new String(cCryptedString);
Here is the 2nd method:
public String decryptString(String aString) {
int iPassStringValue = 0;
int iEncryptKeyValue = 0;
int iDecryptedValue = 0;
char cDecryptedString [] = new char[aString.length()];
for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
iPassStringValue = (int) aString.charAt(iLoop);
iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
iDecryptedValue = iPassStringValue - iEncryptKeyValue;
if (iDecryptedValue < 0)
iDecryptedValue = iDecryptedValue + 256;
cDecryptedString [iLoop] = (char) iDecryptedValue;
return new String(cDecryptedString);
Thanks!!

Similar Messages

  • No warning when assigning to an unsigned char from unsigned int

    Is this an error in VC++, or am I missing something?  The following code should give two warnings for assigning to a smaller type, but only gives one: (compiled as 32 bit)
    unsigned
    char c;
    unsigned
    int i = 24;
    // 32 bit unsigned integer
    unsigned
    long L = 25;
    // Also a 32 bit unsigned integer
    c = L; // Warning C4244
    c = i; // no warning
    This happens in Visual Studios 2005, 2010, 2012, 2013 and 2015, at least.

    Is this an error in VC++, or am I missing something?  The following code should give two warnings for assigning to a smaller type, but only gives one: (compiled as 32 bit)
    unsigned
    char c;
    unsigned
    int i = 24;
    // 32 bit unsigned integer
    c = i; // no warning
    This happens in Visual Studios 2005, 2010, 2012, 2013 and 2015, at least.
    Have you tried it with Warning Level 4?
    In VC++ 2008 Express and W4 I get:
    Warning 2 warning C4244: '=' : conversion from 'unsigned int' to 'unsigned char', possible loss of data
    - Wayne

  • How to covert char[i] to int?

    I have a number (12345678)
    stored in
    char[0]=1
    char[1]=2
    char[2]=3
    char[3]=4
    and so on...........I would like to convert this and stored it as one interger value. That is
    int t=12345678.
    How can I do this?

    Or, you can do like this too,char[] ch = {'1','2','3','4','5','6','7','8'};
         int in = 0;
         int len = ch.length;
         for(int i=0;i<len;i++) {
              in += Character.getNumericValue(ch) * Math.pow(10,(double)(len-i-1));
         System.out.println("Value is : "+in);

  • Convert jstring to char array or int array

    Hi all, please help with the following code. I've tested this code with hard coded char array and it works. Now I have to get the char array from parameter "param1" which is passed from Java.
    The following code compiled with error message:
    error C2223: left of '->GetStringUTFChars' must point to struct/union
    JNIEXPORT void JNICALL Java_DongleSet_DongleWrite(JNIEnv *env,jobject obj,jstring param1){
    char HaspBuffer[500]=(char)env->GetStringUTFChars(param1,NULL);
    int Service=MEMOHASP_WRITEBLOCK;
    int SeedCode=300;
    int LptNum=0;
    int Pass1=pass1;
    int Pass2=pass2;
    int p1=0;
    int p2=12;
    int p3=0;
    int p4=(int)HaspBuffer;
    hasp(Service,SeedCode,LptNum,Pass1,Pass2,&p1,&p2,&p3,&p4);
    I've tried this:char HaspBuffer[500]=env->GetStringUTFChars(param1,NULL);
    And this:char HaspBuffer[500]=(*env)->GetStringUTFChars(param1,NULL);
    All give me errors.
    Please help.

    char * HaspBuffer=(*env)->GetStringUTFChars(param1,NULL); When writing pure C, you have to supply the JNIEnv as first arg to every JNIEnv function pointer.char * HaspBuffer=(*env)->GetStringUTFChars(env, param1, NULL);Look here: http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/jnistring.html

  • USB Output Buffers - int to Hexed Chars

    Hi all
    With regards sending data to a USB device I set up a char like so:
    size_t bufferSize = 8;
    char *buffer = malloc(bufferSize);
    I can then populate my bytes in hex (which seems to be the normal way of doing it).
        buffer[0] = 0xFF;
        buffer[1] = 0xEA;
    The two fold question is will I have any issues if i populate the char buffers with integers?
        int value = 256;
        buffer[0] = value;
    or does it have to be in hex?
    If it requires hex (or even if not cos it would be good to know). What the best way to convert and integer to a hexed char?
    Cheers
    Steve

    It doesn't matter if you specify the value in hexadecimal, decimal, octal or binary (or any other numbering system for that matter).
    A number has the same value no matter what base you use.

  • Output of int value to char

    hi,
    I have written the following code
    class LiteralTest
         public static void main(String[] args)
              System.out.println("Hello World!");
              int true1=100;
              float flt = 17.2345678f;
              short sh = (int)500;
              char a=0x892;
              char b=982;
              char c=(char)70000;
              char d=(char)-98;
              System.out.println(a + " -- "+b+ " -- "+c+ " -- "+d);
    the output is
    Hello World!
    Please explain why the values are '?' and not the actual values?
    Deepali

    And why are you specifying a character with a
    negative number?Casting a negative number to a (unicode) char is valid. For example
                int c = -1279;
                System.out.println(c);           
                char ch = (char)c;
                System.out.println(ch);prints the '&#64257;' character which has unicode value 0xfb01.

  • Wrtie unsigned char and unsigned int into a binary file

    Hi, I need write some data into some specific file format (.ov2) for other applications to read.
    Here is the requirement of the data:
    First byte: An unsigned char value, always "2" means simple POI entry
    Next 4 byte: An unsigned int value,
    Next 4 byte: A signed integer value.
    Next 4 byte: A signed integer value
    then next : A zero-terminated Ascii string
    Here is my code:
                       String name = "name";
                       byte type = 2;
                     int size = name.length() + 13 +1; //1+4+4+4 and there is a 0 at last
                     int a = 1;
                     int b =2;
                     ds.writeByte(type); //1 byte, need save it as unsigned char
                         ds.writeInt(size); //4 //need to be an unsignged int
                         ds.writeInt(ilont); //4 //signed int
                         ds.writeInt(ilatt); //4 //signed int
                         //write zero-terminated ascii string
                         for(int n=0; n<name.length(); n++){
                              ds.writeByte(name.charAt(n));
                         ds.writeByte(0);                    This code could not get the correct result and I think I must do some sign to unsign conversion, but I don't know how to do it. Any help?
    Thanks for you attention.

    You don't have to do anything special at all. What's in a int or a byte is what you, as a programmer, say it is. Java treats int's as signed but, in fact, with 2's complement arithmatic most operations are exactly the same. Load and store, add and subtract - it makes no difference whether a variable is signed or unsigned. It's only when you convert the number, for example to a wider type or to a string representation that you need to know the difference.
    When you read an unsigned byte and you want to widen it to an integer you have to clip the top bytes of the integer e.g.
    int len = input.get() & 0xff;This is because, since java sees a byte as signed it will extend the sign bit into the top bytes of the int. "& 0xff" forces them to zero.
    Writing it, you don't have to do anything special at all - it will autmatically get clipped. The above is probably the only concesion you'll ever need to make to unsigned binary. (You'd need to do the same thing from unsigned int to long, but this almost never happens).
    When I read ov2 files I used a mapped byte buffer, because it allows you to set either big-endian or little-endian and I wasn't sure which ov2 files used. (Sorry, I've forgotten).

  • Int convert to char

    So each char has an integer value representing that char for example a=97 . Now if I have 97 and I want an a, how do I get it?

    Geez, that simple huh? Silly me. Thanx.

  • Change a int into a char or unhash a string hash

    i need to know how to do one of the things in my title thanks :)

    alright thank you very much, i wonder why i didnt
    think of that.. rofl well ty for the feedback.. i
    dont know if im allowed to say this but i gave u 4
    duke starts/points :)Nobody really cares. Thanks. Although after reading the other reply I wonder whether that's what you actually want. I just provided what you asked for.

  • How to call labview DLL from C#, passing char, char[], float[], long, short

    Hi,
    I'm having trouble calling labview dll from C# to perform certain function.
    The function supposed to return the values in the float Analysis[] array. However, when I execute it it only returns zero values.
    It seems that some parameters are not properly passed to the dll.
    Below is the function in the header file:
    void __stdcall Optical_Center(char FileDirectory[], long ImagePtr,
        short int Height, short int Width, char ReadFromFile, float Analysis[],
        long lenAnalysis);
    and my corresponding dll import in c#:
    [DllImport(@"SMIA.dll", CharSet = CharSet.Ansi)]
            public static extern void Optical_Center([MarshalAs(UnmanagedType.LPStr)]string FileDirectory, long ImagePtr,
                short Height, short Width,char  ReadFromFile, IntPtr Analysis,
                long lenAnalysis);
    string str = @"C:\SMIA.raw";
    int len = 3;
    long m_lenAnalysis = 3;
    long m_ImagePtr = 0;
    short m_Height = 2464;
    short m_Width = 3280;
    IntPtr m_PtrArray = Marshal.AllocHGlobal(len * Marshal.SizeOf(typeof(float)));
    char m_ReadFromFile = '1';
    Optical_Center(str,m_ImagePtr,m_Height,m_Width,m_ReadFromFile,m_PtrArray,m_lenAnalysis);
    float[] m_Analysis = new float[len];
    Marshal.Copy(m_PtrArray, floatArray,0,len);
    Marshal.FreeHGlobal(m_PtrArray);
    string printstr = "";
    for (int i=0; i<len; i++)
        printstr = printstr + floatArray[i].ToString() + "\n";       
    MessageBox.Show(printstr);
    Appreciate if anyone can help, thanks.
    KL

    I was just about to post the header file of the DLL, when
    I noticed that there's a function called LVDLLStatus.
    This little thingie turned out to be a rather handy tool.
    With that function I found that in the DLL I had a problem
    with another function that prevented the DLL to be correctly
    loaded.
    This other function in the DLL is for generating digital output
    and it worked as it should, when tested from LV.
    Anyway if someone is interested, I got it working by using
    the LoadLibrary and GetProcAddress function, as in the
    source code thatI posted earlier.
    I will investigate what is wrong with that digital output, and
    post into a another thread if I have problems with that.

  • Comparing a single int to more than one int value?

    Hi is there a way to compare a single int value amongst several ints in one go?
    i know i could do if statements that can compare each int one by one but i was wondering if there is an easier way? like comparing all values amognst eachother
    somthing like
    int i;
    int a,b,c,d,e,f,,g;
    //ints a-g assigned some random numbers
    if(i == a,b,c,d,e,f,g)
          //do somthing here
    }

    i found out a way. i tried this way by using nested for loops and an if statement that compares every single value amongst eachother
    for(int q=0; q < 5; q++)
                ran[q] = (int)(java.lang.Math.random()*52);
            for(int x = 0; x < 5;x++)
                for(int z = 0; z < 5; z++)
                    if(x != z && ran[x] == ran[z])
                        ran[x] = (int)(java.lang.Math.random()*52);
            }

  • Solaris root password is working with extra char/chars appended with it

    Dear forum,
    In our production server, I can login as root with extra char appended end of the actual password
    Exmaple:
    Suppose my password is `hello123`
    But during login all below combinations are working and allowing to login
    hello123*456*
    hello123*4*
    hello123*hello*
    That is, login is not checking further chars after the exact macth with the actuall pass.
    1) But why?
    2) How to prevent this.... any file need to change /etc/default
    NB:
    Dear Nik if you are reading this post... please reply
    Edited by: Myth on Jan 29, 2012 10:28 PM

    It might be worth to note that you will get the crypto algorithm which is defined in /etc/security/crypto.conf
    The default of the crypto.conf is:
    1 crypt_bsdmd5.so.1
    2a crypt_bsdbf.so.1
    md5 crypt_sunmd5.so.1
    5 crypt_sha256.so.1
    6 crypt_sha512.so.1.. if you set CRYPT_DEFAULT in policy.conf to "md5", you will use the crypto algorithm crypto_sunmd5.so.1, if you set CRYPT_DEFAULT to "1" you will get crypt_bsdmd5.so.1.
    Its also worth to notice that the default in Solaris 11 is
    CRYPT_DEFAULT=5
    i.e "crypt_sha256.so.1".
    .7/M.

  • Please confirm: INT columns in calculations return INT results?

    Is it true that, when creating a formula-based column in Answers, dividing an INT typed logical column into an INT typed logical column will result in an INT typed result?
    I must have missed something fundamental here, but it seems counter-intuitive that you can't divide two numbers--regardless of how they are defined--into each other and get a fractional result.
    It only worked as expected when I changed the physical column datatype of one of the logical columns to DOUBLE. Likewise, I suppose I could unmap the logical columns and cast them as DOUBLEs.
    Apparently, I missed something fundamental here. Clarification would be most welcome.
    -John

    The OP doesn't expect those columns to be logged though.  He's performing an update on a table with a unique key, so GoldenGate should be extracting a fieldcomp (compressed update) record type with just the unique key values plus the column he's updating.
    In my example above, I ran a straight forward "add trandata test.rowid_test" command and confirmed that GoldenGate had correctly created a supplemental log group containing my two unique key columns.
    Also I reviewed the extract log and GoldenGate is already identifying the correct key values -
    Wildcard TABLE resolved (entry TEST.*):
      TABLE "TEST"."ROWID_TEST";
    Using the following key columns for source table TEST.ROWID_TEST: COL1, COL2.
    I did actually try the KEYCOLS clause of my TABLE extract parameter at the time, as a possible workaround.  Unfortunately it made no difference.
    I also reviewed the redo content with log miner and every column is logged into the redo, so GoldenGate is just acting on what it finds.  That's why I think really this one is going to be a case of raising a bug report with Oracle Support which will probably end up with the core database team.
    My testing was on 11.2.0.4 by the way.

  • How do you test if a string could be a valid int and then convert to int?

    Hello, my name is Esran41 and I'm new to this site. I'm in computer science one this year and our current assignment is to make a console based Tic-Tac-Toe game. The final program must be able to detect errors in the user's input. For example, if the program asked the user for an int and he typed a character, our program must recognize this, print an error message, and then prompt him for the int again. I also need to know some common string manipulation methods(like String.length) and their syntax too. Again, I'm extremely new to java, so please include code fragments and example programs to demonstrate these methods.
    To sum-it-up, I need to know how to do the following(The syntax):
    Method (1)
    - test an inputed string to see if it's a valid integer
    - report an error to the user if it's not a valid integer
    - if there was an error, prompt the user again
    Method (2)
    - Pass the inputed string as a parameter
    - Convert the string into an integer
    - return the integer
    Also, what is a try-catch statement, what does it do, and how is it implemented?
    Please post any advice or help that you may have pertaining to my problems.
    Thanks!

    Do not insult me. If I could read my computer science
    book, I would. Please don't insult yourself... by pointing out your limitations...
    I will apologize for my cynical remarks... You should see how many requests for " I need help" where the answer could be found so easily...
    But it is quite obvious that you have access to the internet... If you did a search for Java, eventually you would find yourself as Sun's web site... Which means that you would have arrive at this page...
    http://java.sun.com
    and towards the bottom left had corner of that page you would find these links...
    Learning
    New to Java Center
    - Tutorials & Code Camps
    - Online Sessions & Courses
    - Course Certification
    - Instructor-Led Courses
    - Quizzes
    And you will find the same resources that I am using to learn Java...
    I'm looking up this information not only for myself, but for my class too....
    Thus, we are stuck with old computers, about twenty books for 220 kids, and one teacher who is great at >C++, but knows nothing about java.Then print out the Java documentation, goto Kinko's and make copies so that your class can have the reference material available to them, or ask your teacher to... Since he/she will need to learn the language also... But since they have programming experience they will be better able to explain the concepts of programming that you do not understand...
    You can make any excuse for why it is difficult for you to learn, but in the end its totally irrelevant... If the school district cannot provide funding for class material, then instead of complaining with " I don't have a book... " start a community fund raiser to purchase those materials... Goto to the public library and see if they have resources you and your class can utilize... After all, it is your responsibility to educate yourself...
    And most important of all, never ever say anything negative or limiting against yourself...
    Do not insult me. If I could read my computer science book, I would. This is a statement against yourself... What does this statement tell you about yourself... You stated that I should not judge, but here you made a judgement about your own ability to learn...
    To even insinuate that I skip class is an outrage to me. You should watch your tongue and not be so >quick to judge a situation.Why, do you ? Apparently I touched a nerve somewhere... But that does not matter...
    Are you really concerned with what I think of you... If you are then you are a fool...
    What other think or say have nothing to do with you... Do you know me, do I know you...
    The answer is clear... I can give it to you... The Answer is No.
    If you want to learn then learn... Read, Research, Practice and Read again... So simple...
    Anyway... Have fun... Check out the tutorials, learn how to use the API documentation and practice coding...
    and here are those links again...
    The Java Tutorial
    http://java.sun.com/docs/books/tutorial/index.html
    Essentials of the Java Programming Language: A Hands-On Guide, Part 1 and 2
    http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/
    http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/
    Language Essentials Short Course
    http://java.sun.com/developer/onlineTraining/JavaIntro/contents.html
    Others
    The Java Tutorial
    http://java.sun.com/docs/books/tutorial/index.html
    Tutorial Index
    http://java.sun.com/developer/onlineTraining/index.html
    - MaxxDmg...
    - ' He who never sleeps... '

  • Typecasting int into char

    I've got a method I'm working on that looks like this:
    private static String generatePassword()
    String pass = "";
    int randomInt;
    char a;
    for(int i = 1; i <= PASSWORD_LENGTH; i++)
    randomInt = generator.nextInt();
    a = (char)randomInt;
    pass = pass + a;
    System.out.print(pass);
    return pass;
    What I'm trying to do here is create a randomly generated password that consists of five characters. Password_Length is a static variable set to 5. I'm having a problem typecasting the randomInt into a character. Everytime I do this, my display comes back as 'boxes' for each character. If anyone can help, it'd be appriciated.

    private static String generatePassword()
    String pass = "";
    int randomInt;
    char a;
    for(int i = 1; i <= PASSWORD_LENGTH; i++)
                  randomInt = (int)(((double)('z'-'a'))*java.lang.Math.random());
                  if(java.lang.Math.random()<0.5)
                      randomInt -= ('a'-'A');
    a = (char)randomInt;
    pass = pass + a;
    System.out.print(pass);
    return pass;
    }

Maybe you are looking for