I want to convert address to bytes8, but I only managed to convert address to bytes this way:

bytes memory shortAddress = new bytes(8);
for(uint i = 0; i < 8; i++) {
  shortAddress[i] = byte(uint8(uint(newContractAddress) / (2**(8*(19 - i)))));

Now I search for a way to convert from bytes to bytes8, but I think it would be more efficient to go directly from address to bytes8. Is there a way to do so?

  • 1
    Can i ask why you are trying to convert address to bytes8? Address holds 20 bytes of value, hence you will lose some bytes of your address if you do such a thing.
    – Masoud jt
    Jun 1 '20 at 13:29
  • 1
    bytes8 shortAddress = bytes8(newContractAddress);!!! Jun 1 '20 at 14:10
  • @goodvibration That doesn't work because of the reason that i just said. That code works for bytes20 not bytes8.
    – Masoud jt
    Jun 1 '20 at 14:19
  • 1
    Try with pragma solidity 0.4.25;. Solc 0.5.x is probably more restrictive, but I suppose that bytes8 shortAddress = bytes8(bytes20(newContractAddress)); could work in that case. Jun 1 '20 at 14:29
  • 1
    @Masoudjt I explicitly want an only 8 bytes long version of the address like goodvibration states. My contract supplies other contracts. This shortAddress version is stored in a mapping(bytes8 => address), where address is the newContractAddress. The reason is that someone has to type in an address to get to the contract newContractAddress. The whole address would be too much to type in by hand. At all the master contract will not supply more than 10.000 contracts. So I should be fine with this (I check for collisions).
    – timmornYE
    Jun 1 '20 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.