c++和java之间的数据转换
2014-01-31 22:39
218 查看
Converting C++ Unsigned Numbers to Java
Dealing with unsigned values from C++ can seem like a headache sometimes, if you don't understand what's going on "under the hood". Luckily you don't have to understand everything under the hood to read a binary file written by a C++ app in Java or viceversa, just have a vague understanding of the issues involved..
The major differences that can cause challenges are:
1) Figuring out which data types are "equivalent"
2) Java doesn't have unsigned types, but C++ types can be signed or unsigned.
3) Some types just don't have a direct equivalent (eg: C++ float has no exact match in Java)
Here's a table showing how internally C++ (on a 32-bit version of Windows) and Java store integer types:
Size | 1 byte | 2 bytes | 4 bytes | 8 bytes | 16 bytes |
8 bits | 16 bits | 32 bits | 64 bits | 128 bits | |
C++ (on Win32) | byte | short | int/long | long long | __int128 |
Java | byte | short | int | long | BigInteger |
I wanted 4 bytes for my integer, I meant 4 bytes", but that may only work with Microsoft compilers.
Here are some other binary data types that are frequently encountered:
Size | 1 byte | 2 bytes | 4 bytes | 8 bytes | 16 bytes |
8 bits | 16 bits | 32 bits | 64 bits | 128 bits | |
C++ (on Win32) | char/bool | float | double/long double | ||
Java | boolean | char | float | double |
Going from C++ to Java:
C++ Type | Java Type | Read from File ** | Then translate the value |
unsigned byte | (signed) short | byte a = in.readByte(); | short b = (short)(a & 0xff); |
unsigned short | (signed) int | short a = in.readShort(); | int b = a & 0xffff; |
unsigned int/long | (signed) long | int a = in.readInt(); | long b = a & 0xffffffffL; |
float* | float | int a = in.readInt(); | float b = Float.intBitsToFloat(a); |
double | float | float a = in.readFloat(); | //doing nothing extra |
Float.floatBitsToInt(floatValue);to convert in the other direction.
** in refers to a binary input stream type of your choice.
To convert back and forth, you just cast in the to C++ direction. Easy.
Code example: (int or short could be used here just as well)
?
For a C++ unsigned byte (value 0 to 255), mask with 0xff and store the result in a short:
?
Java和C/C++程序实时通讯数据移植问题的研究
点击打开链接相关文章推荐
- hibernate+java+sql 之间数据类型转换关系
- JAVA——基本数据类型之间的自动转换
- Java中数据类型及其之间的转换
- java基本数据类型与包装类之间的转换
- JackSon 数据之间的转换 java
- 初学java——java数据类型,数据类型之间的转换
- java,c,c++ 语言之间基本数据类型的比较
- java与sql 之间数据类型转换关系
- java-包装类、基本数据类型和字符串之间的转换
- Java中数据类型及其之间的转换
- Java File和byte数据之间的转换
- JAVA基本数据类型之间的转换
- Java中数据类型及其之间的转换(转)
- 【java】 基本数据类型之间的转换
- java与c/c++之间的数据交互-----jni点滴
- 常见Java 中数据类型之间的转换的方法!
- java常见数据类型之间的转换
- java Byte和各数据类型(short,int,long,float,double)之间的转换
- java数据之间的转换
- Java 数据类型 和 与String之间的转换