[Closed] [binary] 159 and 13 is 3487
159 in binary is 10011111, 13 in binary is 1101, 3487 in binary is 110110011111
I am getting 159 and 13 from my data (it is stored in two bytes), but I need to combine them in binary to get 3487 (which is a known value). How can I do this with MXS?
(bit.shift 13 8)+159
3487
The bit.shift shifts the bits of 1101 to the left by 8 bits, resulting in 110100000000 (3328 decimal). Then you add 110100000000 + 000010011111 and you get 110110011111 which is 3487 in decimal.
Alternatively, you can say
13*256+159
3487
Don’t have max here right now to test,
but either this can be done by bitshifting (see Bit Operation Methods)
or the ‘crude way’: cast the bits to strings, add them (a+b) and cast them back to binary …
maybe its a start.
Georg
So you need the binary value for 3487? Could always just add the dec values together (+) and write a function to print the binary. I haven’t checked the bit operations, but I’m sure the function I’m refering to exists there.
edit: didn’t see any function for returning binary…
(
fn returnBinary int = (
local placeHolders = #(1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768)
local tempInt = int
local ba = #()
local ti = 1
if int <= placeHolders[placeHolders.count] then (
for i = placeHolders.count to 1 by -1 do (
if tempInt >= placeHolders[i] then (
ba[ti] = "1"
tempInt = tempInt - placeHolders[i]
) else
ba[ti] = "0"
ti+=1
)
local str = ""
local isSet = 0
-- Takes out preceding zeros and returns a string
for i = 1 to placeHolders.count do (
if ba[i] != "0" and isSet == 0 then (
str = str + (ba[i] as string) -- Store
isSet = 1
) else if isSet == 1 then
str = str + (ba[i] as string) -- Store
)
str
) else
return "Integer out of Range"
)
clearListener()
format " 159 = %
" (returnBinary 159)
format " 13 = %
" (returnBinary 13)
format "3487 = %
" (returnBinary 3487)
)
This function will return a string as binary of the given value, currently only supports up to 16 bits, to add more, append to the placeHolders array.
Not sure this was actually requested by the original poster, but here is a slightly simplified version of your function:
--pass an integer and optionally the number of bits to convert and whether to pad
--the string with leading zeros or not:
fn IntToBin theNumber theBits:16 leadingZeros:false =
(
local theString = ""
for i = theBits to 1 by -1 do
theString += (if bit.get theNumber i then
(leadingZeros= true; "1")
else if leadingZeros then "0" else "")
theString
)
IntToBin 159
IntToBin 13
IntToBin 13 theBits:8 leadingZeros:true
IntToBin 3487
--RESULTS:
"10011111"
"1101"
"00001101"
"110110011111"
bows to the brains in the room
That is the trick bobo. I have no idea how you figured that out. Well, that isn’t true, I’ve seen your DVDs, so I have an idea, just not the practical knowledge
That is great moon doggie. Many thanks for taking a stab at my dillema. Cheers.