32bit to long?
BlitzMax Forums/BlitzMax Programming/32bit to long?
| ||
What's the easiest way you know to convert a string with 4 characters in it to a long? There's probably many ways, I just can't find any of them :( I mean from e.g. "7ab4" to an unsigned long? For instance the num equivs of a string is 34,0,58,241 and they become 570440433. Hope it's clear enough, otherwise say something and I'll try to explain further :) |
| ||
Here's what I came up with :/ Anything quicker out there? ' from 4 bytes (8 bit * 4 bytes = 32 bit) to 32 bit unsigned long (blitz long is 64 bit though, but whatever) Function bytes2long:Long(in$) If Len(in) <> 32/8 err("invalid bytes2long input, need 4x8 bit bytes input.") ; Return Local first = in[0] Shl 24' Local second = (in[2] * 256) + in[3] Local result:Long = first + second Return result EndFunction |
| ||
Local s:String="7ab4" Print s.ToLong() Is that what you mean? |
| ||
He wants to treat each character as a digit in a "base 256" number. Here's my attempt. It assumes the string is four characters and each character code is in the range 0-255. BlitzMax uses 16-bit unicode characters so this may not be true if your string was made in China. Note the $FFFFFFFF:Long, just in case the result was a negative integer and got sign-extended to 64 bits. BTL:Long = BytesToLong( Chr($FE) + Chr($DC) + Chr($BA) + Chr($98) ) Print Print BTL Print LongHex( BTL ) Function BytesToLong:Long( in$ ) Local n:Int n = in[0] n = ( n Shl 8 ) | in[1] n = ( n Shl 8 ) | in[2] n = ( n Shl 8 ) | in[3] Return n & $FFFFFFFF:Long End Function |
| ||
Thank you very much Floyd, that is definitely better than mine :) I forgot n[1] as well in mine, hah! |
| ||
Can anyone, maybe Floyd, even, show me how to make the opposite conversion? I don't even know what | does.. |
| ||
I don't even know what | does.. 'Bitwise Or' operation? |
| ||
According to Blitzmax documentation, :| is bitwise or. |
| ||
Looks like this did the trick, for future references.Function long2bytes$(in:Long) Local b1 = (in Shr 24) Mod 256 Local b2 = (in Shr 16) Mod 256 Local b3 = (in Shr 8) Mod 256 Local b4 = (in Shr 0) Mod 256 Print "hej "+b1 Return Chr(b1)+Chr(b2)+Chr(b3)+Chr(b4) EndFunction |
| ||
this is simpler:function long2bytes$(in:long) return hex(in) end function Untested, Might not be faster. |
| ||
He wants base 256, not base 16. It could be speeded up a little with bitwise And. "Mod 256" means discard everything except the last eight bits. So "n Mod 256" has the same effect as "n & $FF", but uses integer division to get the result. |