aspose file tools*
The moose likes Java in General and the fly likes byte array to object casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "byte array to object casting" Watch "byte array to object casting" New topic
Author

byte array to object casting

Thanga prakash Somasundaram
Greenhorn

Joined: Feb 07, 2003
Posts: 21
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...


by,<br />stp<br /> <br />Have a Nice Day...
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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:


Steve
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
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

Joined: Nov 22, 2008
Posts: 18944
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
 
jQuery in Action, 2nd edition
 
subject: byte array to object casting