Java:
byte[] arr1=new byte[]{0x01};
String aa = "helloo";
short[] s1 = new short[1]; // **
s1[0] = 246; // **
Object[] obj = new Object[]{s1,arr1,aa}
C:
signed char a1[] = {0x01};
char *str = "helloo";
short int st1[] = {246}; // **
char* c [] = {st1,str1,c2};
Is short int st1[] = {246} correct? And I am getting this error:
"illegal implicit conversion from 'short *' to 'char *'".
How to assign short to char?
char* c []
is an array of pointers, not an array of chars.
Use something like
short st1[] = { 246 };
char* str = "helloo";
char c [] = {st1[0], str[0], str[1], str[2], str[3], str[4], str[5]};
str[i] gets individual characters, since 'char* str' points to the first element of an array.
If you need an array of string, then make it
char tmp[1024];
// itoa is the conversion of st1[0] to string
char* c[] = { itoa(st1[0], tmp, 10), str };
Cast st1 to a char*. I.e.:
char* c [] = {(char*)st1,str1,c2};
Note that you'll have to cast the pointer back to short* when accessing the elements it points to if you want to get the correct data.
C++ doesn't have a base Object type. You will have to convert your strings all to a specific type.
std::string wtf[]= { std::string(a1, a1+ 1), std::string(st1, st1+ 1), std::string(str) }; // don't forget to #include <string>
In C or C++ there is no common base class for all types (like Java's Object), the best you can use is void* c[]=...; (void* stands for untyped pointers, so it can hold anything) or explicitely cast to the desired type (but then it's undefined to access a short via a char-pointer).
Although its highly not recommended, the rough equivalent of the las line in c is:
void* c [] = {st1,str1,c2};
Related
I have an int array int[] stegoBitsArray = {0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,1...} I want each 8 bits converted to byte and added to byte array which i would later convert to char array because 01101100 is letter "l" and so on so ... So i tried using ByteBuffer but it throws me BufferOverflowException here's my code snippet:
int[] stegoBitsArray = getStegoTextFromImage(stegoImage);
ByteBuffer byteBuffer = ByteBuffer.allocate(stegoBitsArray.length);
for (int i = 0; i < stegoBitsArray.length; i++) {
byteBuffer.putInt(stegoBitsArray[i]);
}
Or it's more better to convert from int array to characters?
To convert from binary to char you have to convert each 8 bit binary into byte and then you can cast from byte to char. Example:
byte b = Byte.parseByte("01100001", 2);
System.out.println((char)b);
Prints
a
How come you can have a value like 0110110001100001 in an integer array. Either it can be stored as a string or there is another way.
You can have an array of integer values something like int array = {123, 456, 333} etc then you can directly convert those integers to characters by looping on the array.
for(int i = 0; i < array.length; i++){
char c = (char)array[i];
System.out.println(c);
}
Or if you want to convert integer to binary then Java supports in Integer class a method called toBinaryString. you can find a good resource for it HERE.
The combination of these two can lead you to your desired solution.
I am really used to java programing now I want to use cpp and I was wondering what is a string called in cpp pretty silly question ? i am trying to use int but the compiler seems not to understand
In C++ a String is called string or preferably std::string and an int is called int. You wouldn't use an int instead of a string.
You appears to have two questions, one about string and another about int, which is confusing, but most likely you have a compilation error in your code which appears to be complaining about int when this is not the problem. I suggest you post a simple example of your code so we can see what you are trying to do.
The following types can be used as "strings" in C++:
1) std::string (defined in <string>)
#include <string>
std::string s = "hello world";
2) array of char
char s[16] = "hello";
char s[] = "world";
3) pointer to char (may actually point to an array)
const char* const globalConstString = "hello world";
void functionThatChangesString(char* s)
{
s[0] = '!';
}
Note that C-style char arrays and char pointers are less "safe" than C++ strings and should be used with care.
Id like to make a simple function, that return value of two Strings, basically:
java
public native String getAppendedString(String name);
c
jstring Java_com_example_hellojni_HelloJni_getAppendedString(JNIEnv* env, jobject thiz, jstring s) {
jstring sx = (*env)->GetStringUTFChars(env, s, NULL);
return ((*env)->NewStringUTF(env, "asd ")+sx);
}
It returns:
jni/hello-jni.c:32: warning: initialization discards qualifiers from pointer target type
jni/hello-jni.c:34: error: invalid operands to binary + (have 'char *' and 'char *')
The retval will be: "asd qwer", how can I do this?
jstring s1 = (*env)->NewStringUTF(env, "456");
jstring s2 = (*env)->NewStringUTF(env, "123");
jstring sall=strcat(s1, s2);
return sall;
Only returns "456"
There are a few issues here:
GetStringUTFChars returns a jbyte * (a null-terminated C string), not a jstring. You need this C string to do string manipulation in C.
You need to call ReleaseStringUTFChars when you're done with it.
You need to allocate enough memory to hold the concatenated string, using malloc.
As ethan mentioned, you need to concatenate your two C strings with strcat. (You cannot do this with the + operator. When applied to a pointer, + returns the pointer from the offset of the original pointer.)
Remember to free the memory you allocated after you're done with it (ie, after it's been interned as a Java string.)
You should do something along the lines of:
char *concatenated;
const jbyte *sx;
jstring retval;
/* Get the UTF-8 characters that represent our java string */
sx = (*env)->GetStringUTFChars(env, s, NULL);
/* Concatenate the two strings. */
concatenated = malloc(strlen("asd ") + strlen(sx) + 1);
strcpy(concatenated, "asd ");
strcat(concatenated, sx);
/* Create java string from our concatenated C string */
retval = (*env)->NewStringUTF(env, concatenated);
/* Free the memory in sx */
(*env)->ReleaseStringUTFChars(env, s, sx);
/* Free the memory in concatenated */
free(concatenated);
return retval;
You can't concatenate two char* with + in c++. Try using strcat instead.
http://www.cplusplus.com/reference/clibrary/cstring/strcat/
EDIT:
from the documentation for strcat:
char * strcat ( char * destination, const char * source );
Concatenate strings
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.
This means that the first argument to strcat needs to have enough memory allocated to fit the entire concatenated string.
I am accessing an ICU4C function through JNI which returns a UChar * (i.e. unicode character array).... I was able to convert that to jbyteArray by equating each member of the UChar array to a local jbyte[] array that I created and then I returned it to Java using the env->SetByteArrayRegion() function... now I have the Byte[] array in Java but it's all gibberish pretty much.. Weird symbols at best... I am not sure where the problem might be... I am working with unicode characters if that matters... how do I convert the byte[] to a char[] in java properly? Something is not being mapped right... Here is a snippet of the code:
--- JNI code (altered slighter to make it shorter) ---
static jint testFunction(JNIEnv* env, jclass c, jcharArray srcArray, jbyteArray destArray) {
jchar* src = env->GetCharArrayElements(srcArray, NULL);
int n = env->getArrayLength(srcArray);
UChar *testStr = new UChar[n];
jbyte destChr[n];
//calling ICU4C function here
icu_function (src, testStr); //takes source characters and returns UChar*
for (int i=0; i<n; i++)
destChr[i] = testStr[i]; //is this correct?
delete testStr;
env->SetByteArrayRegion(destArray, 0, n, destChr);
env->ReleaseCharArrayElements(srcArray, src, JNI_ABORT);
return (n); //anything for now
}
-- Java code --
string wohoo = "ABCD bal bla bla";
char[] myChars = wohoo.toCharArray();
byte[] myICUBytes = new byte[myChars.length];
int value = MyClass.testFunction (myChars, myICUBytes);
System.out.println(new String(myICUBytes)) ;// produces gibberish & weird symbols
I also tried: System.out.println(new String(myICUBytes, Charset.forName("UTF-16"))) and it's just as gebberishy....
note that the ICU function does return the proper unicode characters in the UChar *... somewheres between the conversion to jbyteArray and Java that is is messing up...
Help!
destChr[i] = testStr[i]; //is this correct?
This looks like an issue all right.
JNI types:
byte jbyte signed 8 bits
char jchar unsigned 16 bits
ICU4C types:
Define UChar to be wchar_t if that is
16 bits wide; always assumed to be
unsigned.
If wchar_t is not 16 bits wide, then
define UChar to be uint16_t or
char16_t because GCC >=4.4 can handle
UTF16 string literals. This makes the
definition of UChar platform-dependent
but allows direct string type
compatibility with platforms with
16-bit wchar_t types.
So, aside from anything icu_function might be doing, you are trying to fit a 16-bit value into an 8-bit-wide type.
If you must use a Java byte array, I suggest converting to the 8-bit char type by transcoding to a Unicode encoding.
To paraphrase some C code:
UChar *utf16 = (UChar*) malloc(len16 * sizeof(UChar));
//TODO: fill data
// convert to UTF-8
UConverter *encoding = ucnv_open("UTF-8", &status);
int len8 = ucnv_fromUChars(encoding, NULL, 0, utf16, len16, &status);
char *utf8 = (char*) malloc(len8 * sizeof(char));
ucnv_fromUChars(encoding, utf8, len8, utf16, len16, &status);
ucnv_close(encoding);
//TODO: char to jbyte
You can then transcode this to a Java String using new String(myICUBytes, "UTF-8").
I used UTF-8 because it was already in my sample code and you don't have to worry about endianness. Convert my C to C++ as appropriate.
Have you considered using ICU4J?
Also, when converting your bytes to a string, you will need to specify a character encoding. I'm not familiar with the library in question, so I can't advise you further, but perhaps this will be "UTF-16" or similar?
Oh, and it's also worth noting that you might simply be getting display errors because the terminal you're printing to isn't using the correct character set and/or doesn't have the right glyphs available.
I have some C++ code I'm trying to port to Java, that looks like this:
struct foostruct {
unsigned char aa : 3;
bool ab : 1;
unsigned char ba : 3;
bool bb : 1;
};
static void foo(const unsigned char* buffer, int length)
{
const unsigned char *end = buffer + length;
while (buffer < end)
{
const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
//read some values from struct and act accordingly
}
}
What is the reinterpret_cast doing?
its basically saying the 8 bits represented at the current pointer should be interpreted as a "foostruct".
In my opinion it would be better written as follows:
const unsigned char aa = *buffer & 0x07;
const bool ab = (*buffer & 0x08) != 0;
const unsigned char ba = (*buffer & 0x70) >> 4;
const bool bb = (*buffer & 0x80) != 0;
I think it is far more obvious what is being done then. I think you may well find it easier to port to Java this way too ...
It does what a classic C-style (const foostruct *)buffer would do at worst: tells C++ to ignore all safety and that you really know what you are doing. In this case, that the buffer actually consists of foostructs, which in turn are bit fields overlain on single 8 bit characters. Essentially, you can do the same in Java by just getting the bytes and doing the shift and mask operations yourself.
you have a pointer to unsigned char right? Now imagine that the bits pointed to by the pointer are treated as though it were an object of type foostruct. That's what reinterpret_cast does - it reinterprets the bit pattern to be a memory representation of another type...