Salut nicolas :)

> For positive integers, we have an infinite serie of 0 bits, but we
> don't care, we just don't print them.
> The problem with two complement is that you have an infinite serie of
> leading 1 bits...

Yes :)

> Otherwise, you can access the bit at any rank with bitAt:
> For example, you could use
> bitRepresentation
>       ^(self digitLength * 8 + 1 to: 1 by: -1) collect: [:i | Character
> value: $0 charCode + (self bitAt: i)] as: String

Included in my question is the fact that small integer are encoded on 31 bits 
(may be I'm wrong)
so printing 32 bits represent LargeINteger and so far I want small integetr so 
was my assumption correct?
and what would be a good method to return bitString of a Small Integer.s

2 raisedTo: 29 
        returns 536870912 

536870912 class
        returns SmallInteger

2 raisedTo: 30 
        returns 1073741824

1073741824 class
        returns LargePositiveInteger

-1073741824 class 
        returns SmallInteger

2 class maxVal 
        returns 1073741823

-1 * (2 raisedTo: (31-1)) 
        returns -1073741824
        
(2 raisedTo: 30) - 1
        returns 1073741823


> 
> The first bit will aways be the sign with the + 1 trick.
> 
> Nicolas
> 
> 2011/7/4 Sven Van Caekenberghe <[email protected]>:
>> 
>> On 04 Jul 2011, at 20:16, Stéphane Ducasse wrote:
>> 
>>> I would like to see the two complement representation of numbers.
>> 
>> This is what I do, for reading/writing unsigned or two complement signed 
>> integer from/to byte streams.
>> 
>> Note that two complement is only defined for a specific number size, 8, 16, 
>> 32 bits.
>> 
>> unsignedToSigned: integer size: size
>>        ^ integer < (2 raisedTo: size - 1)
>>                ifTrue: [ integer ]
>>                ifFalse: [ (self twoComplement: integer size: size) negated ]
>> 
>> signedToUnsigned: integer size: size
>>        ^ integer negative
>>                ifTrue: [ self twoComplement: integer size: size ]
>>                ifFalse: [ integer ]
>> 
>> twoComplement: integer size: size
>>        | mask |
>>        mask := (2 raisedTo: size) - 1.
>>        ^ mask bitAnd: ((integer abs bitXor: mask) + 1)
>> 
>> These are also very handy in this context (I believe I once submitted that 
>> as an issue):
>> 
>> integerFromByteArray: bytes
>>        | integer |
>>        integer := 0.
>>        bytes withIndexDo: [ :each :index |
>>                integer := integer + (each bitShift: (bytes size - index) * 
>> 8) ].
>>        ^ integer
>> 
>> and Integer>>#asByteArrayOfSize:
>> 
>> Once you have a byte representation, you can render it as bits as well.
>> 
>> Sven
>> 
>> 
>> 
>> 
> 


Reply via email to