[.net] Reading and writing ints/shorts/floats into a byte[]

Started by
5 comments, last by jods 18 years, 9 months ago
...and the other way around I haven't found a good way to do it. So far all I've been able to do is make a BinaryReader/Writer to do it for me. Is there a simpler way without concatenating/breaking up the data manually (bitwise operations)? The stream thing is far too complicated when all I want to do is write or read a single number from/into an array of bytes. It was much easier in C++ when I could do all the untypesafe things I wanted [sad].
____________________________________________________________AAAAA: American Association Against Adobe AcrobatYou know you hate PDFs...
Advertisement
Well, if you are using C# you can always use unsafe code. But that is much too effort.

The ".Net Way" would be to use the BitConverter class. It can convert all of the basic data types to byte arrays and back, so it should do the job quite well.
Turring Machines are better than C++ any day ^_~
Yay. That solves half my problem.

My other problem is this: I have an array that needs to change sizes periodically, so I'm using a List<T> (it's a List<byte>). Unfortunately, none of the Array.Copy methods work with List. Is there a work around instead of using List.ToArray everywhere? This is in a performance critical section so I'm trying to get rid of as many news and array allocations as I can.
____________________________________________________________AAAAA: American Association Against Adobe AcrobatYou know you hate PDFs...
Ah, you are using the Beta. I haven't sat down much with it yet, and am not quite sure where MSDN is hiding the .Net 2 documentation. I am guessing though that List is similar to the currect IList containers. If so, it should have a Clone() method that will copy all of those bytes to another List.
Turring Machines are better than C++ any day ^_~
.Net 2.0 Docs
Thanks guys. Everything is working well now except for I still can't copy a section of a byte[] into a List<byte>. If I can get this down, my code will be more elegant than my C++ version was.

I suppose I could change the List<byte> to an Array, but I've grown to like the explicit typing of the generics. With Arrays, everything is just an object, and keeping track of what casts I can do gets on my nerves.
____________________________________________________________AAAAA: American Association Against Adobe AcrobatYou know you hate PDFs...
Well, there are functions like AddRange, InsertRange, etc. that take an IEnumerable as input (arrays are). But they don't let you choose a range in the array.

Anyway, why don't you just write a function that does what you need ?
[source lang=csharp]void CopyRange<T>(List<T> output, T[] input, int outputStartIdx, int inputStartIdx, int count){   for (int i = 0; i < count; i++)      output[outputStartIdx++] = input[inputStartIdx++];}


Regards,
jods

This topic is closed to new replies.

Advertisement