user1539497
user1539497

Reputation: 51

Char data type in C/C++

I am trying to call a C++ DLL in Java. In its C++ head file, there are following lines:

    #define a '102001'
    #define b '102002'
    #define c '202001'
    #define d '202002'

What kind of data type are for a, b, c, and d? are they char or char array? and what are the correpsonding data type in Java that I should convert to?

Upvotes: 5

Views: 698

Answers (2)

House.Lee
House.Lee

Reputation: 251

I might try to answer the first two questions. Being not familiar with java, I have to leave the last question to others.

Single and double quotes mean very different things in C. A character enclosed in single quotes is just the same as the integer representing it in the collating sequence(e.g. in ASCII implementation, 'a' means exactly the same as 97).

However, a string enclosed in double quotes is a short-hand way of writing a pointer to the initial character of a nameless array that has been initialized with the characters between the quotes and an extra character whose binary value is 0.

Because an integer is always large enough to hold several characters, some implementations of C compilers allow multiple characters in a character constant as well as a string constant, which means that writing 'abc' instead of "abc" may well go undetected. Yet, "abc" means a pointer points to a array containing 4 characters (a,b,c,and \0) while the meaning of 'abc' is platform-dependent. Many of the C compiler take it to mean "an integer that is composed somehow of the values of the characters a,b,and c.

For more informations, you might read the chapter 1.4 of the book "C traps and pitfalls"

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

As Mysticial pointed out, these are multicharacter literals. Their type is implementation-dependent, but it's probably Java long, because they use 48 bits.

In Java, you need to convert them to long manually:

static long toMulticharConst(String s) {
    long res = 0;
    for (char c : s.toCharArray()) {
        res <<= 8;
        res |= ((long)c) & 0xFF;
    }
    return res;
}

final long a = toMulticharConst("102001");
final long b = toMulticharConst("102002");
final long c = toMulticharConst("202001");
final long d = toMulticharConst("202002");

Upvotes: 5

Related Questions