Cairo's playground bitwise operations challenge

Hello, any clue in how to solve bitwise opertion’s challenge?

So far I tried the below code:

%builtins bitwise

from starkware.cairo.common.bitwise import bitwise_and, bitwise_xor
from starkware.cairo.common.cairo_builtins import BitwiseBuiltin

// Returns the xor of the last two hexadecimal digits.
func xor_last_hex_digits{bitwise_ptr: BitwiseBuiltin*}(x: felt) -> (res: felt) {
    // Fix and uncomment the line below.
    let (shifted_digit0) = bitwise_and(x, 0xF0);
    tempvar digit0 = shifted_digit1 / 0x10;

    let (shifted_digit1) = bitwise_and(x, 0xF0);
    tempvar digit1 = shifted_digit1 / 0x10;

    return bitwise_xor(digit0, digit1);
}

func main{bitwise_ptr: BitwiseBuiltin*}() {
    let (res) = xor_last_hex_digits(0x1234);
    assert res = 7;

    return ();
}

I get the following result:

Error: code:25:5: Cannot convert the return type of bitwise_xor to the return type of xor_last_hex_digits.
    return bitwise_xor(digit0, digit1);
    ^*********************************^
10 Likes

Solution:

func xor_last_hex_digits{bitwise_ptr: BitwiseBuiltin*}(x: felt) -> (res: felt) {
    // Fix and uncomment the line below.
    let (digit0) = bitwise_and(x, 0x0F);  // bitwise_and(0x1234, 0x0F) ==> bitwise_and(1234,0f) hexadecimal

    let (shifted_digit1) = bitwise_and(x, 0xF0); // 30
    tempvar digit1 = shifted_digit1 / 0x10; // returns modulus.
    let (xor_res) = bitwise_xor(digit0, digit1);
    return (res = xor_res);
7 Likes

You must store the result of the bitwise_xor() function call in a variable and then return it.

Solution:

%builtins bitwise

from starkware.cairo.common.bitwise import bitwise_and, bitwise_xor
from starkware.cairo.common.cairo_builtins import BitwiseBuiltin

// Returns the xor of the last two hexadecimal digits.
func xor_last_hex_digits{bitwise_ptr: BitwiseBuiltin*}(x: felt) -> felt {
    // Fix and uncomment the line below.
    let (digit0) = bitwise_and(x, 0x0F);  // with x = 0x1234, return 4

    let (shifted_digit1) = bitwise_and(x, 0xF0);
    tempvar digit1 = shifted_digit1 / 0x10;

    let (digit0_xor_digit1) = bitwise_xor(digit0, digit1); 
    return digit0_xor_digit1;
}

func main{bitwise_ptr: BitwiseBuiltin*}() {
    let res = xor_last_hex_digits(0x1234);
    assert res = 7;
    return ();
}
8 Likes

:argentina: :argentina: :argentina: :argentina: :argentina: :argentina:
¡Vamoos Damian! buenas :saluting_face:

2 Likes