'Solidity issue "TypeError: Explicit type conversion not allowed from "uint256" to "address""

problem is in the last line of code

function bytesToAddress(bytes memory b) public view returns (address) {
    uint256 result = 0;
    for (uint256 i = b.length - 1; i + 1 > 0; i--) {
        uint256 c = uint256(uint8(b[i]));

        uint256 to_inc = c * (16**((b.length - i - 1) * 2));
        result += to_inc;
    }
    return address(result);

Can't figure out how to make this function work properly. Any help is appreciated



Solution 1:[1]

function bytesToAddress(bytes memory b) public view returns (address) {
  uint result = 0;
  for (uint i = 0; i < b.length; i++) {
      uint c = uint(b[i]);
      if (c >= 48 && c <= 57) {
          result = result * 16 + (c - 48);
      }
      if(c >= 65 && c<= 90) {
          result = result * 16 + (c - 55);
      }
      if(c >= 97 && c<= 122) {
          result = result * 16 + (c - 87);
      }
  }
  return address(result);
}

bytes32 values are in hexadecimal format. Here is the table show how ranges in if statement is calculated

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1