Hi guys!
I need to convert an integer to binary, it would be something in the code itself, as if it had a
DECL I=10 and the corresponding binary of I is returned. I didn't find the solution in the manual and I would like to see with you some possible solution. thanks
Workvisual
convert an integer to binary KRC
-
ycrideas -
January 5, 2023 at 4:45 PM -
Thread is Unresolved
-
- Go to Best Answer
-
The Binary would be in the form of an array with 16 positions
ex:Number: 3
Array: F F F F F … F F T T
-
- Best Answer
then just write your own... assuming this is 16-bit
Code
Display MoreDEF DECODE16(val1:in, val2[]:out) DECL INT val1, i, n DECL BOOL val2[] i=1 FOR n=1 to 16 val2[n]=(val1 B_AND i)<>0 i=i+i ENDFOR END DEFFCT INT ENCODE16(val1[]:out) DECL BOOL val1[] DECL INT i, n, tmp tmp=0 i=1 FOR n=1 to 16 IF Val1[n]==TRUE THEN tmp=tmp+i ENDIF i=i+i ENDFOR RETURN tmp ENDFCT
then you could use them to do something like
-
thanks panic mode
-
morning, I managed to convert the integer, but the values that are filled in the array are the other way around, could you help me?
in this case there will always be 16 array positions, but only the first ones will actually be used
another thing man, I didn't quite understand what this ENCODE16 function does, can you explain? thank you so much
-
the values that are filled in the array are the other way around
Just reverse index...
N goes through values 1..16 so to get 16..1 replace N with 17-N:
val2[17-n]=(val1 B_AND i)<>0
ENCODE16 is inverse of DECODE16. It does exactly the opposite...
-
hi, I have a big problem,
in this case it doesn't work as expected, in fact the array will be inverted, but it must be taken into account that several integers will not occupy the 16 positions of the array.for example the number 42 would be (0000000000010101) and in fact it should be (1010100000000000).
when I use val2[n]=(val1 B_AND i)<>0 the expected array would be 1010100000000000 and it returns 0101010000000000, that is, the actually occupied positions are inverted
-
42 binary is:
0010 1010
Your assumption 0001 0101 is wrong. You can see it on one sight. Lowest bit must be zero, as 42 is an even number.
-
...it returns 0101010000000000
42 is 0000000000101010 but you wanted bit array reversed. so program returns correct output.