According to the Solidity documentation one can access the byte at position k in for example a Bytes16 variable source with the following code:

pragma solidity ^0.4.8;

contract example {

 Bytes16 source=0xa9c40ddcb43ebbc83add97b8f9f361f1;

 function returnByte(uint k) returns (bytes1 a) {
    a = source[k];
    return a;       


However, as stated in the documentation, this only works for read access. What is the best way to write at a defined position k into the Bytes16 source?


Here is how you can do this with a bit of bit trickery (at the cost of 450 gas):

function setByte(bytes16 x, uint8 i, byte b)  returns (bytes16) {
    bytes16 mask = bytes16(0xff) << i*8;
    return (x & ~mask) | (bytes16(b) >> (15-i)*8);
  • How to do this to only get the certain position without change, let's say getByte(bytes 16, uint8 i) returns (bytes2) – Eduardo Pereira Aug 16 '18 at 5:23
  • 1
    @EduardoPereira return bytes2(x >> i*8); – max taldykin Aug 16 '18 at 11:06

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.