Implicit conversion??

Started by
7 comments, last by Zahlman 18 years, 4 months ago
In c#, this is what im doing:

            byte[] temp = new byte[2];
            pChunk.bytesRead = m_FilePointer.Read(temp, 0, 2);
            pChunk.ID = ushort.Parse(temp.ToString());
Why doesnt this work, i get number was not in correct format. Thanks for any help
http://www.thedizzle.com
Advertisement
I'm no expert, but are you certain that temp.ToString() is what you expect?

Most times with file reading I've seen some Formatting call used with bytes from files.

[edit: how are you opening the file? binary file, text?]
I haven't gotten to file i/o in C# yet, but the output of the following code seems like a good sign of what's wrong:
byte[] temp = new byte[2];temp[0] = 1;temp[1] = 2;System.Console.WriteLine(temp.ToString());

CM
using System;using System.IO;using System.Collections.Generic;using System.Text;class Program {    static void Main(string[] args) {        /*if (args.Length < 1) {            return;        }*/        //FileInfo        fi=new FileInfo(args[0]);        FileInfo fi = new FileInfo(@"test.txt");          StreamReader fr = fi.OpenText();        ushort us =new ushort();        string s=fr.ReadLine();                               Console.WriteLine("s: {0}", s);        us=ushort.Parse(s);        Console.WriteLine("us: {0}", us);    }}


To parse out multiple shorts on a line, use regex's to split the line string to smaller strings.

[edit: I've known C# for about 3 days, so it's highly plausible that there's a better way]
that would be great except i need to read only two bytes, not a line. Its being read as a binary file. I need to convert two bytes/chars to a ushort.
http://www.thedizzle.com
        // *snip* above code.        FileStream   fs = new FileStream(@"test.bin", FileMode.OpenOrCreate);        BinaryWriter fwb = new BinaryWriter(fs);        fwb.Write((UInt16)us);        fwb.Close();        fs.Close();        Console.WriteLine("Bin-write: {0}", us);        fs = new FileStream(@"test.bin", FileMode.Open);        BinaryReader frb = new BinaryReader(fs);        us=frb.ReadUInt16();        Console.WriteLine("Bin-read: {0}", us);        frb.Close();        fs.Close();


Doing a simple open with a FileInfo does seem to yield improper results, probably because the filestream isn't close()'d nicely before the second call opens it or some buffer isn't flushed or somesuch.
I think you guys are making things a little too complicated. The correct solution is relatively easy and painless.

Quote:Original post by rgirard413
In c#, this is what im doing:
            byte[] temp = new byte[2];            pChunk.bytesRead = m_FilePointer.Read(temp, 0, 2);            pChunk.ID = ushort.Parse(temp.ToString());


Why doesnt this work, i get number was not in correct format.

Thanks for any help

Parse is for transforming strings to integers. Try printing the result of temp.ToString() and you'll find that it's probably not what you expected.

Instead, use the BitConverter class ("Converts base data types to an array of bytes, and an array of bytes to base data types.") and its corresponding ToUInt16(byte[]) method.

Remember, UInt16 isn't CLS-compliant, so if you're looking for portability here, stick with Int32.

Hope that helps,
-- k2
- k2"Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ} | {Blog/Journal} | {[email=kkaitan at gmail dot com]e-mail me[/email]} | {excellent webhosting}
That does help!
If you know the endianness, you can do it manually:

pChunk.ID = (temp[0] << 8) | temp[1];

Depending on C#'s semantics for signedness of types and so on, you may need to do something with the second byte in order to have it treated as unsigned. (In Java, you can do it for example as (temp[0] << 8) | (temp[1] & 0xff).) That's for big-endian of course; for little-endian, swap the indices around.

This topic is closed to new replies.

Advertisement