Proektsoftbg / Calcpad

Free and open source software for mathematical and engineering calculations.
https://calcpad.eu
MIT License
338 stars 42 forks source link

Feature request: Support for hex and binary literals #333

Open Jostikas opened 1 month ago

Jostikas commented 1 month ago

In computer science and embedded device engineering, it often makes sense to work wit integers in a different base than decimal. For example: Most ADCs have resolutions in powers of 2, so ADC full range would be something like (1<<14)-1 for a 14-bit ADC. This is easily expressed in hexadecimal as 0x3FFF (binary 0b0011_1111_1111_1111), while in decimal it is the highly unintuitive 16383. So when I debug an ADC, and it returns 0x3b26, it would make sense to, in Calcpad, do

Vref=0.6V
adc=0x3b26
res=0x3fff
gain=1/6
input = adc/res*(Vref/gain)

Instead, I have to first perform the base conversion somewhere else to arrive at

Vref=0.6V
adc=15142
res=16383
gain=1/6
input = adc/res*(Vref/gain)

Occasionally it also makes sense to represent data in binary, when for example, bit 13 of a register means "reboot" and bit 14 means "smoke while doing so". Showing the contents of a 32-bit register as 0b00000000_00000000_01100000_00000000 makes it easy to see what bits are set.

So I would like if there were native support for the 0x and 0b integer prefixes, along with a way to force a result into the corresponding format (with truncation to integer optional, "not an integer" error as an alternative).

As Calcpad is (as far as I can tell) based on Python, which has native support for these representations (along with support for literals with _ as group separators), this seems like it should mostly be a parsing engine change, not a math engine change.

Fixed or floating point conversions (except perhaps IEEE 754, if the implementer feels particularly masochistic) are usually too custom to merit incusion in a general purpose software package, so are explicitly excluded from this feature request.

Jostikas commented 1 month ago

(I'm aware that for many common ADC implementations, I should use 0x4000, not 0x3FFF, in the calculation. That's just an additional complexity in the process to keep in mind, so removing decimal conversion as an additional stumbling block would really benefit the mind).

Proektsoftbg commented 1 month ago

Hi!

Thank you for your suggestion. I have tought about implementing different numerical systems, other than decimal. Calcpad is not based on Python (it has even nothing to do with it), but it is still just a matter of parsing and rendering the number back to text. I will consider adding this option to future versions. Also, we can implemplement any base-n system quite easily. This is simple math.