Created
April 1, 2022 09:06
-
-
Save erikcorry/7f2627f6fb39f67587e2ffd83cb05128 to your computer and use it in GitHub Desktop.
Sign-extend and duplicate 16 bit values in Toit using blit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bitmap show blit | |
import expect show * | |
/** | |
Takes a byte array of little endian 16 bit values. | |
Returns a new byte array of little endian 32 bit values, sign extended. | |
For each input 16 bit value there are two (copied) 32 bit output values. | |
*/ | |
expand input/ByteArray -> ByteArray: | |
output := ByteArray input.size * 4 | |
// Sign extend. | |
2.repeat: | |
blit input[1..] output[2 + it..] input.size / 2 | |
--source_pixel_stride=2 | |
--destination_pixel_stride=8 | |
--lookup_table=SIGN_EXTEND_TABLE | |
// Expand. | |
blit input output 2 | |
--destination_line_stride=8 | |
// Duplicate the 32 bit values. | |
blit output output[4..] 4 | |
--source_line_stride=8 | |
--destination_line_stride=8 | |
return output | |
test in/ByteArray expect/ByteArray -> none: | |
output := expand in | |
expect_equals output expect | |
main: | |
test #[0, 0] #[0, 0, 0, 0, 0, 0, 0, 0] | |
test #[4, 0] #[4, 0, 0, 0, 4, 0, 0, 0] | |
test #[4, 255] #[4, 255, 255, 255, 4, 255, 255, 255] | |
test #[4, 255, 3, 5] #[4, 255, 255, 255, 4, 255, 255, 255, 3, 5, 0, 0, 3, 5, 0, 0] | |
SIGN_EXTEND_TABLE ::= #[ | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, | |
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment