File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

byte array to object casting

 
Thanga prakash Somasundaram
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have byte array containing data of a C structure.
I want to cast it to an object, so that i can get the values of that object.
for eg:
In C,
struct dd
{
int a;
float f;
}

struct dd* ptr;
char buff[500];
// buff has data from the file
ptr=buff;
// i will be able to access the fields of the
// structure
ptr->a;
ptr->f;
In Java,
class dd
{
int a;
int ff;
}
I have the data in the byte buff[]..
How to cast it to a object of dd?
help me...
 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let me see if I understand. You have a byte array
called buf where buf[0] = a, and buf[1] = ff.
You want to create an object of type dd to store
this data in. If this is the case, look at
the code below:
 
John Lee
Ranch Hand
Posts: 2545
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thanga prakash Somasundaram:
I have byte array containing data of a C structure.
I want to cast it to an object, so that i can get the values of that object.
for eg:
In C,
struct dd
{
int a;
float f;
}

struct dd* ptr;
char buff[500];
// buff has data from the file
ptr=buff;
// i will be able to access the fields of the
// structure
ptr->a;
ptr->f;
In Java,
class dd
{
int a;
int ff;
}
I have the data in the byte buff[]..
How to cast it to a object of dd?
help me...


There is no pointer in Java. You can do:
dd d = new dd() ;
d.a = buff[0] ;
d.ff = buff[1] ;
.....
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thanga prakash Somasundaram:
I have byte array containing data of a C structure. I want to cast it to an object, so that i can get the values of that object.

Have a look at the java.nio.* package and pay special attention to the IntBuffer and FloatBuffer classes on top of the ByteBuffer class (that will generate the first two objects for you).
The 'd.i= buff[0]; d.f= buff[1]' approach simply doesn't work because ints and floats take up more than one single byte.
kind regards
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic