News:

  • April 09, 2026, 05:11:13 PM

Login with username, password and session length

Author Topic: How Do I Convert A Decimal Number Containing Either Zeros or Ones to Bit Of Word  (Read 141 times)

Mike Nash

  • Hero Member
  • *****
  • Posts: 652
Example: 
If D1=111 decimal, I want to get:
D2:0 = 1
D2:1 = 1
D2:3 = 1
D2:4 = 0
D2:5 = 0
D2:6 = 0
D2:7 = 0
(D2 = 7 decimal)

I'm hoping it doesn't require looping. The D1 value is actually from an 8 character ASCII string "00000111" converted with STR2INT.

BobO

  • Host Moderator
  • Hero Member
  • *****
  • Posts: 6154
  • Yes Pinky, Do-more will control the world!
You have a binary string and want the decimal representation? STR2INT set to base 2 will give you exactly what you want.
"It has recently come to our attention that users spend 95% of their time using 5% of the available features. That might be relevant." -BobO

Mike Nash

  • Hero Member
  • *****
  • Posts: 652
I have a decimal value that if a digit is 1, I need to set a bit for that digit to use in logic and HMI.
So if D1 is 10,000,001 in decimal, I need to set bits to correspond to the digits that are one, so D2 = 1000 0001 binary.

This is a serial response to queries over StreamIn/Out for custom protocol.

BobO

  • Host Moderator
  • Hero Member
  • *****
  • Posts: 6154
  • Yes Pinky, Do-more will control the world!
It sounded like you started with an ASCII string of a binary value, then converted it as decimal through STR2INT? If so just change STR2INT to use base 2 (it defaults to 10) and you have exactly what you're asking for. If you really are starting with a decimal representation of a binary number, then I would reverse the process and use STRPRINT to go to the binary string, then use STR2INT(base 2) to convert it.
"It has recently come to our attention that users spend 95% of their time using 5% of the available features. That might be relevant." -BobO

Mike Nash

  • Hero Member
  • *****
  • Posts: 652
Thanks BobO, I figured it was going to be more involved. It is indeed a decimal number, unfortunately (for me). I am "decoding" quite a lot of strings to extract data and how each is to be interpreted. This is based on which HMI screen is displaying to keep the number of parameters somewhat frequently updated at 9600 baud. Each has to be requested individually, wait for response, decode it, then do stuff.

Did I mention these are mostly not even contiguous? The discrete bits being sent as digits slipped by me. Since only about 9 of these are coded in this fashion it screws up being easy to decode.

Mike Nash

  • Hero Member
  • *****
  • Posts: 652
Oh! I just tried the STRPRINT STR2INT Base 2. That works great!

Thanks!