Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Converting Back from Decimal to Byte

Converting Back from Decimal to Byte

Scheduled Pinned Locked Moved C#
csharplinqdata-structureshelptutorial
16 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Richard DeemingR Richard Deeming

    Yes, you just need to change the path in your WriteAllBytes call:

    // Write the bytes to a different file:
    string filePath2 = Path.Combine("C:\\A Different Folder", Path.GetFileName(filePath));
    File.WriteAllBytes(filePath2, data2);


    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

    C Offline
    C Offline
    computerpublic
    wrote on last edited by
    #7

    /*
    IT DOESN'T WORK..I ADDED THE LINE:::string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
    I RAN THE PROGRAM AND CHECK FOLDER WAS EMPTY. THE FILE WAS NOT WRITTEN TO THE NEW LOCATION. ALL I WANT TO DO SEE ANOTHER INSTANCE OF THE FILE
    */

    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Applica
    {
    class Program
    {
    static void Main(string[] args)
    {
    DirectoryInfo da = new DirectoryInfo("C:\\Folder");
    FileInfo[] Arr = da.GetFiles();
    if (Arr.Length == 0)
    {
    throw new InvalidOperationException("No files found.");
    }
    // No need to loop through the array just to get the last item:
    FileInfo ap = Arr[Arr.Length - 1];
    long Totbyte = ap.Length;
    string filePath = ap.FullName;
    Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
    // GetTempFileName *creates* the file, so it always exists:
    string temPath = Path.GetTempFileName();
    byte[] data = File.ReadAllBytes(filePath);
    File.WriteAllBytes(temPath, data);
    // Convert the bytes to decimals:
    decimal[] arry = new decimal[Totbyte];
    for (int count = 0; count < data.Length; count++)
    {
    arry[count] = data[count];
    }
    // Convert the decimals back to bytes:
    byte[] data2 = new byte[Totbyte];
    for (int count = 0; count < arry.Length; count++)
    {
    data2[count] = (byte)arry[count];
    }
    // Just to prove they're the same:
    if (data2.Length != data.Length)
    {
    throw new InvalidOperationException("Wrong length!");
    }
    for (int index = 0; index < data.Length; index++)
    {
    if (data[index] != data2[index])
    {
    throw new InvalidOperationException("Data has changed at index " + index);
    }
    }
    // Write the bytes back to the file:
    string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
    File.WriteAllBytes(filePath, data2);
    // To prove they're still the same:
    data = File.ReadAllBytes(temPath);
    data2 = File.ReadAllBytes(filePath);
    if (

    Richard DeemingR 1 Reply Last reply
    0
    • C computerpublic

      /*
      IT DOESN'T WORK..I ADDED THE LINE:::string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
      I RAN THE PROGRAM AND CHECK FOLDER WAS EMPTY. THE FILE WAS NOT WRITTEN TO THE NEW LOCATION. ALL I WANT TO DO SEE ANOTHER INSTANCE OF THE FILE
      */

      using System;
      using System.IO;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;

      namespace Applica
      {
      class Program
      {
      static void Main(string[] args)
      {
      DirectoryInfo da = new DirectoryInfo("C:\\Folder");
      FileInfo[] Arr = da.GetFiles();
      if (Arr.Length == 0)
      {
      throw new InvalidOperationException("No files found.");
      }
      // No need to loop through the array just to get the last item:
      FileInfo ap = Arr[Arr.Length - 1];
      long Totbyte = ap.Length;
      string filePath = ap.FullName;
      Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
      // GetTempFileName *creates* the file, so it always exists:
      string temPath = Path.GetTempFileName();
      byte[] data = File.ReadAllBytes(filePath);
      File.WriteAllBytes(temPath, data);
      // Convert the bytes to decimals:
      decimal[] arry = new decimal[Totbyte];
      for (int count = 0; count < data.Length; count++)
      {
      arry[count] = data[count];
      }
      // Convert the decimals back to bytes:
      byte[] data2 = new byte[Totbyte];
      for (int count = 0; count < arry.Length; count++)
      {
      data2[count] = (byte)arry[count];
      }
      // Just to prove they're the same:
      if (data2.Length != data.Length)
      {
      throw new InvalidOperationException("Wrong length!");
      }
      for (int index = 0; index < data.Length; index++)
      {
      if (data[index] != data2[index])
      {
      throw new InvalidOperationException("Data has changed at index " + index);
      }
      }
      // Write the bytes back to the file:
      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
      File.WriteAllBytes(filePath, data2);
      // To prove they're still the same:
      data = File.ReadAllBytes(temPath);
      data2 = File.ReadAllBytes(filePath);
      if (

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #8

      computerpublic wrote:

      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

      If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

      // Write the bytes to a different file:
      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
      File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      C 3 Replies Last reply
      0
      • Richard DeemingR Richard Deeming

        computerpublic wrote:

        string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

        If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

        // Write the bytes to a different file:
        string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
        File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        C Offline
        C Offline
        computerpublic
        wrote on last edited by
        #9

        It works. Thank you very much Richard.

        1 Reply Last reply
        0
        • Richard DeemingR Richard Deeming

          computerpublic wrote:

          string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

          If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

          // Write the bytes to a different file:
          string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
          File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          C Offline
          C Offline
          computerpublic
          wrote on last edited by
          #10

          /*
          I AM NOW TRYING TO CONVERT BYTE TO STRING AND ALSO CONVERTING BACK FROM STRING TO BYTE.
          I ALSO WANT TO SEE THE OUTPUT.
          I AM NOT UNDERSTING WHY I AM GETTING AN ERROR.
          THE OUTPUT INFORMATION IS BELOW::

          Total Bytes = 8228730 bytes

          Unhandled Exception: System.InvalidOperationException: Data has changed at index
          310
          at Applica.Program.Main(String[] args) in C:\Documents and Settings\shampro\D
          esktop\Program.cs:line 41
          Press any key to continue . . .
          */

          using System;
          using System.IO;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;

          namespace Applica
          {
          class Program
          {
          static void Main(string[] args)
          {
          DirectoryInfo da = new DirectoryInfo("C:\\Folder");
          FileInfo[] Arr = da.GetFiles();
          if (Arr.Length == 0)
          {
          throw new InvalidOperationException("No files found.");
          }
          // No need to loop through the array just to get the last item:
          FileInfo ap = Arr[Arr.Length - 1];
          long Totbyte = ap.Length;
          string filePath = ap.FullName;
          Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
          // GetTempFileName *creates* the file, so it always exists:
          string temPath = Path.GetTempFileName();
          byte[] data = File.ReadAllBytes(filePath);
          File.WriteAllBytes(temPath, data);
          // Convert the bytes to string:
          string arry = ASCIIEncoding.ASCII.GetString(data);
          Console.WriteLine(arry);
          // Convert the string back to bytes:
          byte[] data2 = Encoding.ASCII.GetBytes(arry);
          foreach (byte element in data2)
          {
          Console.WriteLine("{0}={1}",element ,(char)element);
          }
          // Just to prove they're the same:
          if (data2.Length != data.Length)
          {
          throw new InvalidOperationException("Wrong length!");
          }
          for (int index = 0; index < data.Length; index++)
          {
          if (data[index] != data2[index])
          {
          throw new InvalidOperationException("Data has changed at index " + index);
          }
          }
          // Write the bytes back to the file:
          string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
          File.WriteAllBytes(filePath2, data2);
          // To prove they're

          C Richard DeemingR 2 Replies Last reply
          0
          • C computerpublic

            /*
            I AM NOW TRYING TO CONVERT BYTE TO STRING AND ALSO CONVERTING BACK FROM STRING TO BYTE.
            I ALSO WANT TO SEE THE OUTPUT.
            I AM NOT UNDERSTING WHY I AM GETTING AN ERROR.
            THE OUTPUT INFORMATION IS BELOW::

            Total Bytes = 8228730 bytes

            Unhandled Exception: System.InvalidOperationException: Data has changed at index
            310
            at Applica.Program.Main(String[] args) in C:\Documents and Settings\shampro\D
            esktop\Program.cs:line 41
            Press any key to continue . . .
            */

            using System;
            using System.IO;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;

            namespace Applica
            {
            class Program
            {
            static void Main(string[] args)
            {
            DirectoryInfo da = new DirectoryInfo("C:\\Folder");
            FileInfo[] Arr = da.GetFiles();
            if (Arr.Length == 0)
            {
            throw new InvalidOperationException("No files found.");
            }
            // No need to loop through the array just to get the last item:
            FileInfo ap = Arr[Arr.Length - 1];
            long Totbyte = ap.Length;
            string filePath = ap.FullName;
            Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
            // GetTempFileName *creates* the file, so it always exists:
            string temPath = Path.GetTempFileName();
            byte[] data = File.ReadAllBytes(filePath);
            File.WriteAllBytes(temPath, data);
            // Convert the bytes to string:
            string arry = ASCIIEncoding.ASCII.GetString(data);
            Console.WriteLine(arry);
            // Convert the string back to bytes:
            byte[] data2 = Encoding.ASCII.GetBytes(arry);
            foreach (byte element in data2)
            {
            Console.WriteLine("{0}={1}",element ,(char)element);
            }
            // Just to prove they're the same:
            if (data2.Length != data.Length)
            {
            throw new InvalidOperationException("Wrong length!");
            }
            for (int index = 0; index < data.Length; index++)
            {
            if (data[index] != data2[index])
            {
            throw new InvalidOperationException("Data has changed at index " + index);
            }
            }
            // Write the bytes back to the file:
            string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
            File.WriteAllBytes(filePath2, data2);
            // To prove they're

            C Offline
            C Offline
            computerpublic
            wrote on last edited by
            #11

            SORRY, THE PROBLEM IS ON LINE 61. BEFORE THE PROBLEM WAS ON LINE 41, BUT I ADDED COMMENTS AND SHIFTED THE ENTIRE THING DOWN.

            1 Reply Last reply
            0
            • C computerpublic

              /*
              I AM NOW TRYING TO CONVERT BYTE TO STRING AND ALSO CONVERTING BACK FROM STRING TO BYTE.
              I ALSO WANT TO SEE THE OUTPUT.
              I AM NOT UNDERSTING WHY I AM GETTING AN ERROR.
              THE OUTPUT INFORMATION IS BELOW::

              Total Bytes = 8228730 bytes

              Unhandled Exception: System.InvalidOperationException: Data has changed at index
              310
              at Applica.Program.Main(String[] args) in C:\Documents and Settings\shampro\D
              esktop\Program.cs:line 41
              Press any key to continue . . .
              */

              using System;
              using System.IO;
              using System.Collections.Generic;
              using System.Linq;
              using System.Text;

              namespace Applica
              {
              class Program
              {
              static void Main(string[] args)
              {
              DirectoryInfo da = new DirectoryInfo("C:\\Folder");
              FileInfo[] Arr = da.GetFiles();
              if (Arr.Length == 0)
              {
              throw new InvalidOperationException("No files found.");
              }
              // No need to loop through the array just to get the last item:
              FileInfo ap = Arr[Arr.Length - 1];
              long Totbyte = ap.Length;
              string filePath = ap.FullName;
              Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
              // GetTempFileName *creates* the file, so it always exists:
              string temPath = Path.GetTempFileName();
              byte[] data = File.ReadAllBytes(filePath);
              File.WriteAllBytes(temPath, data);
              // Convert the bytes to string:
              string arry = ASCIIEncoding.ASCII.GetString(data);
              Console.WriteLine(arry);
              // Convert the string back to bytes:
              byte[] data2 = Encoding.ASCII.GetBytes(arry);
              foreach (byte element in data2)
              {
              Console.WriteLine("{0}={1}",element ,(char)element);
              }
              // Just to prove they're the same:
              if (data2.Length != data.Length)
              {
              throw new InvalidOperationException("Wrong length!");
              }
              for (int index = 0; index < data.Length; index++)
              {
              if (data[index] != data2[index])
              {
              throw new InvalidOperationException("Data has changed at index " + index);
              }
              }
              // Write the bytes back to the file:
              string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
              File.WriteAllBytes(filePath2, data2);
              // To prove they're

              Richard DeemingR Offline
              Richard DeemingR Offline
              Richard Deeming
              wrote on last edited by
              #12

              Hardly surprising - ASCII encoding can only cope with 128 characters. If any of your bytes are greater than or equal to 128, the ASCIIEncoding class[^] will replace them with a question mark. When you re-encode the string, these bytes will have been replaced with the value 63. You still haven't explained what you're trying to achieve.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              C 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                Hardly surprising - ASCII encoding can only cope with 128 characters. If any of your bytes are greater than or equal to 128, the ASCIIEncoding class[^] will replace them with a question mark. When you re-encode the string, these bytes will have been replaced with the value 63. You still haven't explained what you're trying to achieve.


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                C Offline
                C Offline
                computerpublic
                wrote on last edited by
                #13

                I am trying to become a good programmer, but following the examples in the books sometimes does not work. The professor in the school is also very suspicious. I think she is reading the chapters before the class and pretending like she knows. She never answers direct questions. The answer always come in the next class session. I feel I am on my own with c#. Sometimes I feel that the people who write the books, don't know any c# at all. How it is possible for examples in text not to work. I encounter this problem many times and it is very frustrating. To add to the frustration, I go online to the help forums and I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know. I am trying to learn from people who know, that is what I am trying to achieve. I hope this answers the question.

                C Richard DeemingR 2 Replies Last reply
                0
                • C computerpublic

                  I am trying to become a good programmer, but following the examples in the books sometimes does not work. The professor in the school is also very suspicious. I think she is reading the chapters before the class and pretending like she knows. She never answers direct questions. The answer always come in the next class session. I feel I am on my own with c#. Sometimes I feel that the people who write the books, don't know any c# at all. How it is possible for examples in text not to work. I encounter this problem many times and it is very frustrating. To add to the frustration, I go online to the help forums and I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know. I am trying to learn from people who know, that is what I am trying to achieve. I hope this answers the question.

                  C Offline
                  C Offline
                  computerpublic
                  wrote on last edited by
                  #14

                  Could you please kindly respond to my new post "Out Of Memory Exception"? It is a completely different question, so I didn't thought it wise to post it here. Thank You.

                  1 Reply Last reply
                  0
                  • C computerpublic

                    I am trying to become a good programmer, but following the examples in the books sometimes does not work. The professor in the school is also very suspicious. I think she is reading the chapters before the class and pretending like she knows. She never answers direct questions. The answer always come in the next class session. I feel I am on my own with c#. Sometimes I feel that the people who write the books, don't know any c# at all. How it is possible for examples in text not to work. I encounter this problem many times and it is very frustrating. To add to the frustration, I go online to the help forums and I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know. I am trying to learn from people who know, that is what I am trying to achieve. I hope this answers the question.

                    Richard DeemingR Offline
                    Richard DeemingR Offline
                    Richard Deeming
                    wrote on last edited by
                    #15

                    computerpublic wrote:

                    I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know.

                    We don't ask what you're trying to achieve because we don't want you asking questions; it's just that, if you tell us what you want the code to do, we might be able to point you towards a better solution. It's often better to take a step back and look at the bigger picture of what you want to do, rather than fixating on why a particular line of code doesn't do what you expect. :) Your professor certainly doesn't sound like she's up to the job. Have you tried talking to your tutor about your concerns?


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                    1 Reply Last reply
                    0
                    • Richard DeemingR Richard Deeming

                      computerpublic wrote:

                      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

                      If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

                      // Write the bytes to a different file:
                      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                      File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      C Offline
                      C Offline
                      computerpublic
                      wrote on last edited by
                      #16

                      /*If I am generating a series of bits ONE BIT AT A TIME for example {10101000}. How do I turn the entire series into one byte after I generate the 8th bit. I am trying to back track using the example you gave me, but I am getting some errors.*/

                      using System;
                      using System.IO;
                      using System.Collections;
                      using System.Collections.Generic;
                      using System.Linq;
                      using System.Text;

                      namespace Applica
                      {
                      class Program
                      {
                      static Random _random = new Random ();////Start: Fisher-Yates Array Shuffler
                      public static void Shuffle<T>(T[] array)
                      {
                      var random = _random;
                      for (int i = array.Length; i > 1; i--)
                      {
                      int j = random.Next(i);
                      T tmp = array[j];
                      array[j] = array[i - 1];
                      array[i - 1] = tmp;
                      }
                      }////////////////////////////////////////////End: Fisher-Yates Array Shuffer
                      static void Main(string[] args)
                      {
                      byte[] outdata = new byte[1];
                      BitArray[] bits2 = new BitArray[8];
                      char[] array = {'1','0','1','0','1','0','1','0'};
                      Shuffle(array);
                      for (int i = 0; i < 8; i++)
                      bits2[i] = array[1];//Error: Cannot Implicitly convert type 'char' to 'System.Collections.BitArray'
                      outdata[i] = (byte)bits2;//Error: Cannot convert type 'System.Collections.BitArray[]' to 'byte'
                      }
                      }
                      }

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups