So the bits that are left shifted to bit number >7 return when the right shift is performed. The problem is that, even though Value is an 8 bit type, the bitwise operations are performed in 32 bit registers. Obviously if it is already a Byte then you don't need the bitwise and.Īnd the original 32 bit function would read better like this, in my humble opinion.Įarlier versions of this answer had the following incorrect attempt to solve the problem: function IntToBinByte(Value: Byte): string If (Value shr (8-i)) and 1 = 0 then beginĪnd call it like this str := IntToBinByte(Value and $ff) Īssuming that Value is a 32 bit data type. Like this: function IntToBinByte(Value: Byte): string And I find this double shifting to be a little obscure. If ((Value shl (24+i-1)) shr 31) = 0 then beginĪ version that might be easier to understand, in relation to the original, would be like this: function IntToBinLowByte(Value: LongWord): string įrankly however it is better to operate on a single byte. To make your code work you need this: function IntToBinLowByte(Value: LongWord): string And so they return when you shift to the right. You are not getting all the bits to the left of the target bit to fall off the end. However, your data type is still 32 bits, and so you are not shifting far enough. Then when you shift right again, we shift all the way to the other end. By doing so, all bits to the left are shifted off the end and lost. The left shift in the code is meant to shift the bit you are interested in to the very left hand edge of the data type. PS: Asking in learning purposes, solved my case with Copy(Result, 25, 8) at the end of the first function, because needed 8 chars long string passed, but I really want to understand what's going on. what am I missing here, and don't understand? :/ Tried to change LongWord to Integer and Byte as well, but got the same results. If ((Value shl (i-1)) shr 7) = 0 then beginīut I get results as they follow: 1: 00000001 However, since I only needed 8 chars long string result, I changed the numbers in a function to 8 to get this: function IntToBin(Value: LongWord): string If ((Value shl (i-1)) shr 31) = 0 then begin I used function function IntToBin(Value: LongWord): string As already asked David in a comment of an answer here, I'm really interested on how this function works, since I can't seem to get the same (correct) values if changing result length from 32 to 16 or 8.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
February 2023
Categories |