2

I am trying to implement the following lines in python to C#

final_reg = hex(gain_st)+'400020'

After that, I need to write final_reg to a register which in python was written this way.

serial.write(int('A', 16), int(final_reg, 16))

But In C# I implemented my serial.write using a function called write_word_segment_addr(); For Ex, if I want to write 90 to A I write like this currently:

mem.write_word_segment_addr(0x7c032, 0x00000090);      //A

How do I convert gain_st which is a UInt32 to hex and then add 400020 and then convert it to 0x format seen above so that I may write to my register?

Alex Callaway
  • 45
  • 1
  • 6
  • 2
    Have a look at this post: https://stackoverflow.com/questions/1139957/convert-integer-to-hexadecimal-and-back-again – Stefan Sep 27 '19 at 06:27
  • To hexadecimal `string`: `string s = intValue.ToString("x");` back to `int`: `int v = Convert.ToInt32(s, 16);` – Dmitry Bychenko Sep 27 '19 at 06:51

2 Answers2

1
final_reg = gain_st.ToString("x") + "400020";
mem.write_word_segment_addr(10, int.Parse(final_reg, NumberStyles.HexNumber));
shingo
  • 18,436
  • 5
  • 23
  • 42
  • `serial.write` which was my method in python, I have already re-written a method in C# called `write_word_segment_addr`. I need to add a `0x` in front of final_reg – Alex Callaway Sep 27 '19 at 06:53
  • 1
    Why do you need to add `0x`? `0xa` and `10` are totally the same integer. – shingo Sep 27 '19 at 07:36
0

In case of C# you can use string interpolation:

 // 0x is not required for further conversion and can be dropped
 string final_reg = $"0x{gain_st:x}{400020}";

If you want to convert final_reg to integer, use Convert:

 write_word_segment_addr(Convert.Int32("A", 16), Convert.Int32(final_reg, 16));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215