0

Is there a simply way to convert decimal/ascii 6 bit decimal numbers from 1 to 100 to binary representation? To be more specific im interested in 6 bit binary ascii. So I made this to get int 32. For example "u" is changed to 61 instead 117 in standard decimal ascii. Then this 61 is needed to be "111101" instead of traditional "01110101" but after this 48 + 8 math it's not important as now it's normal binary, just with 6 bits used.

foreach (char c in partToDecode)
                        {
                            var sum = c - 48;
                            if (sum>40)
                            {
                                sum = sum - 8;
                            }

Found this, but i don't have a clue how to traspose it to c#

void binary(unsigned n) {
   unsigned i;
   // Reverse loop
   for (i = 1 << 31; i > 0; i >>= 1)
       printf("%u", !!(n & i));
}

. . .

binary(65);
Jacob2396
  • 1
  • 1
  • 2
    `string result = Convert.ToString(source, 2).PadLeft(6, '0');` – Dmitry Bychenko Jan 06 '21 at 20:48
  • @DmitryBychenko: I tried that already, underlined 2 and CS1503 "cannot convert from int to System.Iformat.Provider" – Jacob2396 Jan 06 '21 at 20:53
  • 2
    @Jacob2396 `source` has to be an `int`, `byte`, `long`, or `short` for that to work. If you have an unsigned type you'll have to cast it. – juharr Jan 06 '21 at 20:54
  • 2
    Does this answer your question? [Convert integer to binary in C#](https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp) – Charlieface Jan 06 '21 at 21:24

1 Answers1

1

You can try Convert.ToString, e.g.

  int source = 61;

  // "111101"
  string result = Convert.ToString(source, 2).PadLeft(6, '0');

Fiddle

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Working well after changing to int (actually deleting conversion to string ) I have one more problem. Inside forloop i i have loop j, after closing j, inside first i have a foreach loop like in a quest. Im writing it to a file with File.AppendAllText(path, string). But behind this foreach loop i would want to have a new line. I tried FileAppend (no possibility without an argument), streamwritter was accepted but not only it didnt write new line, fileappend didn't write anything too. I closed stream so i dont know where is the problem. What should i use.So \n after iterating – Jacob2396 Jan 06 '21 at 21:13
  • @Jacob2396: Could you, please, turn `File.AppendAllText` problem into a new *question* with the code (example) and actual / desired behaviour? It's *difficult* to obtain relevant data from the *comment*. – Dmitry Bychenko Jan 06 '21 at 21:17