Slicing 32bit variable into 8bit array

25 views
Skip to first unread message

Matthias

unread,
Mar 22, 2020, 5:30:10 AM3/22/20
to blech-lang
Hi Blech Team,

I recently wanted to implement the following in Blech:

var a: bits32 = 0xA1B2C3D4
var arr: [4]bits8

arr
[0] = ((a & 0x_00_00_00_FF) >> 0) as bits8 // 0xD4
arr[1] = ((a & 0x_00_00_FF_00) >> 8) as bits8 // 0xC3
arr[2] = ((a & 0x_00_FF_00_00) >> 16) as bits8 // 0xB2
arr[3] = ((a & 0x_FF_00_00_00) >> 24) as bits8 // 0xA1

However, according to the compiler, donwcasting from bits32 to bits8 is not allowed. Is there any alternative for slicing one 32bit value into four 8bit values?

Thanks in advance!

Best regards,
Matthias

Franz-Josef Grosch

unread,
Mar 23, 2020, 10:21:27 AM3/23/20
to blech-lang
Hi Matthias,

Currently we only support, what is sometimes called guaranteed conversion. Using the 'as' operator.
Guaranteed conversion can be verified by the compiler.

I propose to also introduce forced conversion using the operator 'as!' .
The compiler would reject forced conversion if it is not necessary. For example in  'a as! bits32' or 'a as! nat32'.

In the future we will distinguish debug and and release code generation. In debug code, forced conversion can trap, if the runtime value does not "fit" into the converted type. In release code we would use the semantics of C's downcast.

Maybe we will also have  'as?' as soon as we introduce exceptions - which we already planned. 'as?' will throw an exception instead of trapping - also in the release code. Exceptions have to be caught by an exeception handler, for a programm, that is accepted by the compiler.

In your example you would have to use 'as!' instead of 'as'. For the moment we only generate release code.

I still have to check the consequences, before I start implementing this feature.

All the best,
Franz-Josef

Matthias

unread,
Mar 25, 2020, 2:46:35 AM3/25/20
to blech-lang
Hi Franz-Josef,

thanks for the feedback! For me, the concept of the 'as!' operator sounds reasonable. This makes it explicit / obvious that the conversion (down cast) might induce loss of information.

Best regards,
Matthias
Reply all
Reply to author
Forward
0 new messages