473,721 Members | 2,023 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting arrays into byte arrays

Hi there,
I am trying to write a method that accepts an array of any primitive
type and will return the same array without copying memory as an array
of bytes.

ie. I'd like to be able to do something like:

char[] chars = "Hello!";
byte[] bytes = (byte[]) chars;

which obviously won't work.

Is there any way of casting arrays?

Thanks for any help you can give me.

Matt
Jul 17 '05 #1
5 13919
On Wed, 06 Aug 2003 11:36:59 +0100, matt melton <ha***********@ yahoo.co.uk>
two-finger typed:
Hi there,
I am trying to write a method that accepts an array of any primitive
type and will return the same array without copying memory as an array
of bytes.
You will have to overload the method (i.e. write a different method for
each type of array).

ie. I'd like to be able to do something like:

char[] chars = "Hello!";
You are assigning a String object to an array ?
Use:
String hello = "Hello!" ;
char [] chars = new char [hello.length()];
hello.getChars( 0,hello.length( ),chars,0);

Or:
char [] chars = getChars("Hello !");

with an extra (local) method:
public char [] getChars(String s) {
char [] chars = new char [s.length()];
hello.getChars( 0,s.length(),ch ars,0);
}
byte[] bytes = (byte[]) chars;
bytes and chars are two different things.
chars are 16 bit (Unicode), bytes are 8 bit.

The resulting bytes out of a string would have to represent an encoding of
the string to support Unicode characters above the codevalue 255.

Have a look at the String API for more information.

Converting doubles and floats into bytes may pose even more of a challenge,
if you want the storage to be according to IEEE standards.
Have you looked at Serialization ?
which obviously won't work.

Is there any way of casting arrays?

Thanks for any help you can give me.

Matt

Cheers.
Jul 17 '05 #2

"matt melton" <ha***********@ yahoo.co.uk> wrote in message news:3F******** *******@yahoo.c o.uk...
Hi there,
I am trying to write a method that accepts an array of any primitive
type and will return the same array without copying memory as an array
of bytes.

ie. I'd like to be able to do something like:

char[] chars = "Hello!";
byte[] bytes = (byte[]) chars;

which obviously won't work.

Is there any way of casting arrays?


Actually, you don't need to 'cast' arrays of primitives to arrays of bytes.

What you need is something else (I don't know what, exactly), but you
think, for some reason, that your goal can be acomplished by doing
something like that (treating a block of memory like an array of bytes,
regardless of what's inside that block. That's precisely what you shouldn't
even think about, in Java. Go back to C for stunts like that. (-: )

So, it would be better if you went one step back and said what you really
wanted to do, instead of asking detailed help on something that could
easily be a bad idea in the first place.

Jul 17 '05 #3
Hi

I might need to elaborate on what I'm really trying to do,

I am writing an API to allow simple message passing of arrays between
VM's on different machines. I'd like to use UDP and Datagrams for the
trasfer ( I have my reasons, they may not be valid though ).
I want it to be as light weight and quick as possible:
So just a simple byte tag to identify the type of the array, rather than
serializing the array.
As little memory copying between the array itself and a DatagramPacket
as possible, the minimum being zero if it is feasible ( which I am
beginning to think isn't).

What I really want is to be able to view a primitive array,
as an array of any other primitive type.

ie

byte[16] bytearray int[4] intarray double[2] doublearry
0_____8 0_______8 0_______8
0 |__A__| 0 | A | | A |
1 |__B__| |___B___| | B |
2 |__C__| 1 | C | | C |
3 |__D__| |___D___| |___D___|
4 |__E__| 2 | E | | E |
5 |__F__| |___F___| | F |
6 |__G__| 3 | G | | G |
7 |__H__| |___H___| |___H___|
8 |__I__| 4 | I | | I |
9 |__J__| |___J___| | J |
10|__K__| 5 | K | | K |
11|__L__| |___L___| |___L___|
12|__M__| 6 | M | | M |
13|__N__| |___N___| | N |
14|__O__| 7 | O | | O |
15|__P__| |___P___| |___P___|

all pointing at the same array in memory.
I can use a java.nio.ByteBu ffer to put a double into a ByteArray, and
view it as both 8 bytes and 2 integers etc.

but I cannot create an array of one type and then place it straight into
a DatagramPacket constructor as the buffer to use for the data like
this:

sendDouble( double[] data , offset , length , address , port){

//copy double[] data into new byte[] newData

dsocket.send( new DatagramPacket( newData , offset , length,
address , port));
}

without doing a memory copy of some kind to get the data out of the
double array into a byte array even though they contain the same
bytes...
hope that makes sense.

Is java designed to prevent this kind of memory tampering, even if the
view would be read only?

I'll just have to settle for a single memory copy( + the one from the
DatagramPacket to the network interface w3hich I can't do anything
about) I suppose.

Thanks
Neomorph wrote:

On Wed, 06 Aug 2003 11:36:59 +0100, matt melton <ha***********@ yahoo.co.uk>
two-finger typed:
Hi there,
I am trying to write a method that accepts an array of any primitive
type and will return the same array without copying memory as an array
of bytes.


You will have to overload the method (i.e. write a different method for
each type of array).

ie. I'd like to be able to do something like:

char[] chars = "Hello!";


You are assigning a String object to an array ?
Use:
String hello = "Hello!" ;
char [] chars = new char [hello.length()];
hello.getChars( 0,hello.length( ),chars,0);

Or:
char [] chars = getChars("Hello !");

with an extra (local) method:
public char [] getChars(String s) {
char [] chars = new char [s.length()];
hello.getChars( 0,s.length(),ch ars,0);
}
byte[] bytes = (byte[]) chars;


bytes and chars are two different things.
chars are 16 bit (Unicode), bytes are 8 bit.

The resulting bytes out of a string would have to represent an encoding of
the string to support Unicode characters above the codevalue 255.

Have a look at the String API for more information.

Converting doubles and floats into bytes may pose even more of a challenge,
if you want the storage to be according to IEEE standards.
Have you looked at Serialization ?

which obviously won't work.

Is there any way of casting arrays?

Thanks for any help you can give me.

Matt


Cheers.

Jul 17 '05 #4
Hi there,
it's just a question of effeciency, I don't like to copy memory when I
don't have to, but If I must I must. If it makes the program more
stable secure etc..
then I'll have to like it.
It just seemed a bit of waste to have the same information stored in
two places with identical data just so it can be accessed in a
particular way. I guess it's due to the protability reasons etc...

Cheers

Actually, you don't need to 'cast' arrays of primitives to arrays of bytes.

What you need is something else (I don't know what, exactly), but you
think, for some reason, that your goal can be acomplished by doing
something like that (treating a block of memory like an array of bytes,
regardless of what's inside that block. That's precisely what you shouldn't
even think about, in Java. Go back to C for stunts like that. (-: )

So, it would be better if you went one step back and said what you really
wanted to do, instead of asking detailed help on something that could
easily be a bad idea in the first place.

Jul 17 '05 #5
On 7 Aug 2003 01:25:18 -0700, ha***********@y ahoo.co.uk (matt melton)
two-finger typed:
Hi there,
it's just a question of effeciency, I don't like to copy memory when I
don't have to, but If I must I must. If it makes the program more
stable secure etc..
then I'll have to like it.
It just seemed a bit of waste to have the same information stored in
two places with identical data just so it can be accessed in a
particular way. I guess it's due to the protability reasons etc...
Not just for portability, but also for security and bug repellant.

Basically data in memory is always typed in java, to stop the possibility
of bugs with respect to wrong interpretation of memory content (as code for
example - which is an occurence that makes hacking Microsoft Operating
Systems, browsers and even their game console so relatively easy).

An array, for example, is more than just a series of memory locations fora
specific datatype, it also holds the unchangable length of the array.

You could probably use JNI if you are so bent on reusing memory, but that
would make your application non-portable and more open to bugs...

Cheers

Actually, you don't need to 'cast' arrays of primitives to arrays of bytes.

What you need is something else (I don't know what, exactly), but you
think, for some reason, that your goal can be acomplished by doing
something like that (treating a block of memory like an array of bytes,
regardless of what's inside that block. That's precisely what you shouldn't
even think about, in Java. Go back to C for stunts like that. (-: )

So, it would be better if you went one step back and said what you really
wanted to do, instead of asking detailed help on something that could
easily be a bad idea in the first place.


Cheers.
Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
10307
by: Hal Vaughan | last post by:
If I have a byte and I convert it to string (String sData = new String(byte bData), then convert it back (byte bData = sData.getBytes()), will all data be intact, or do Strings have problems with bytes that are not printable characters? I've tested this and it seems to work fine, but I want to make sure there isn't some condition or situation I'm not aware of that could cause problems. I'm doing this because it's easier to do some of my...
3
2341
by: Pete Davis | last post by:
I've never done this in C# so I don't know what the appropriate way of doing it is. I've got an array of bytes and I need to convert the array into "usable" data. For example, the first 4 bytes need to be converted to an enum. The next 4 bytes to a 32-bit int. And so on. I'm basically populating a struct with the data. How does one do this in C#? Thanks.
2
7368
by: Matt | last post by:
I just wanted to know if I am converting to/from streams the easiest and correct way. I am performing the following statements to convert byte arrays to and from streams during different processing in my application: Here is a sample where I convert from a stream to a byte array: strm = mqMsg.BodyStream; BinaryReader br = new BinaryReader(strm); byteArray= br.ReadBytes(Convert.ToInt32(strm.Length));
5
4449
by: _BNC | last post by:
I've converted " byte" to "byte *" at times, using 'unsafe' and fixed { .... }, but the reverse does not seem to work. In this case, a C++ DLL returns a byte * and a length. What is the best way to convert these to straight C#-compatible straight " byte" arrays? PS: The C++ DLL is actually managed and I have access to the source. Perhaps there is a simpler syntax for doing the conversion there, and returning a C# compatible array...
2
10358
by: Shreddy | last post by:
Hi, I'm trying (or struggling) to convert some C code to C#. The existing C client is sending a structure via a TCP socket to a network server. The structure contains a mix of int and char data types . I can re-create the structure in c# with LayoutKind.Explicit, but how do I convert this structure to a byte array for use with the Socket.Send() method?
4
4021
by: movieknight | last post by:
Hi, I have an application that stores raw .wav files (and also jpgs/bitmaps) within strings, and I need to sometimes convert these strings to byte arrays, and sometimes go from byte arrays back to strings. How do I convert this raw data from one format to another? I don't think system.text.encoding is useful here as the data is not in any particular encoding format, it's just raw data and it needs to stay
9
30515
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats. How can I convert the sets of 4 bytes to floats? Thanks, Greg Book
5
2127
by: redeagle | last post by:
In VB6, the code for a structure is Structure zFuheader Dim Id1(80) As Byte Dim Id2(80) As Byte End Structure However, in .NET, it doesn't let you declare the array size in the structure.
12
2686
by: steven acer | last post by:
hello, i have a java app that constructs an xml from a specific file format and vice versa. i've been asked to convert it to c++, but im not an expert in c++, actually im mere beginner you can say. i got a couple of questions though: 1- is there any equivalent to java's Stream classes(ByteArrayInputStream,InputStreamRedare,DataInputStream ..) 2- how to open a stream on a byte ( char) array in c++ in order to read it as text. i have a...
0
9373
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9227
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9138
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5992
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4491
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4761
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3201
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2584
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2137
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.