# How to convert B512 type to u64 type

**URL:** https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425
**Category:** Sway
**Tags:** testnet, feedback
**Created:** [August 7, 2024, 9:09am UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425 "2024-08-07T09:09:02Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![div-lync](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/div-lync/32/3441_2.png) [@div-lync](https://forum.fuel.network/u/div-lync)
#### Post date: [August 7, 2024, 9:09am UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/1 "2024-08-07T09:09:02Z")

</div>

- I want to convert B512 type to u64 , I can convert B512 to u256 succesfully , But I am getting issues while converting B512 to u64

```auto
 fn b512_to_u64(value: B512) -> Option<u64> {
    // Extract the lower 256 bits from the B512 value
    let b_256 = value.bits()[0];
    let u_256 = b_256.as_u256();
    let u_64 = <u64 as TryFrom<u256>>::try_from(u_256);
    u_64
}

```

- This is the error

```plaintext
 /home/divy/fuel-lync/Fuel-Contracts/lootbox/src/main.sw:165:49
    |
163 | 
164 | let u_256 = b_256.as_u256();
165 | let u_64 = <u64 as TryFrom<u256>>::try_from(u_256);
    | ^^^^^ This parameter was declared as type u64, but argument of type u256 was provided.
166 | u_64
167 | }

```

Is there any way to convert B512 to u64?

- `fuelup show` output

```auto
   Default host: x86_64-unknown-linux-gnu
fuelup home: /home/divy/.fuelup

Installed toolchains
--------------------
latest-x86_64-unknown-linux-gnu (default)
nightly-x86_64-unknown-linux-gnu
testnet-x86_64-unknown-linux-gnu (override)

active toolchain
----------------
testnet-x86_64-unknown-linux-gnu (override), path: /home/divy/fuel-lync/Fuel-Contracts/lootbox/fuel-toolchain.toml
 forc : 0.61.2
   - forc-client
     - forc-deploy : 0.61.2
     - forc-run : 0.61.2
   - forc-crypto : 0.61.2
   - forc-debug : 0.61.2
   - forc-doc : 0.61.2
   - forc-fmt : 0.61.2
   - forc-lsp : 0.61.2
   - forc-tx : 0.61.2
   - forc-wallet : 0.8.1
 fuel-core : 0.31.0
 fuel-core-keygen : 0.31.0

fuels versions
--------------
forc : 0.64.0
forc-wallet : 0.64.0

```

---

<div class="post-metadata">

### Author: ![naz3eh](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/naz3eh/32/2025_2.png) [@naz3eh](https://forum.fuel.network/u/naz3eh)
#### Post date: [August 7, 2024, 9:47am UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/2 "2024-08-07T09:47:27Z")

</div>

To convert a `B512` type to `u64` , you would need to extract the bytes and then convert those bytes to `u64` .

Here’s how you can extract the lower 64 bits from the `B512` type and convert it to `u64`

```auto
fn b512_to_u64(value: B512) -> Option<u64> {
    // Extract the lower 256 bits from the B512 value
    let b_256 = value.bytes[0];
    let u_256 = b_256.0; // Extract the inner [u8; 32] array

    // Convert the first 8 bytes to u64
    let mut bytes = [0u8; 8];
    bytes.copy_from_slice(&u_256[0..8]);
    Some(u64::from_le_bytes(bytes))
}

```

Here, I have adjusted slice value to convert the first 8 bytes of the lower `b256` value to `u64` . Adjust the slice accordingly if you need a different part of the `b256` value.

Please check this out and lmk how it goes.

---

<div class="post-metadata">

### Author: ![div-lync](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/div-lync/32/3441_2.png) [@div-lync](https://forum.fuel.network/u/div-lync)
#### Post date: [August 7, 2024, 12:17pm UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/3 "2024-08-07T12:17:47Z")

</div>

> [@naz3eh](#):
>
> ```auto
> fn b512_to_u64(value: B512) -> Option<u64> {
> // Extract the lower 256 bits from the B512 value
> let b_256 = value.bytes[0];
> let u_256 = b_256.0; // Extract the inner [u8; 32] array
> 
> // Convert the first 8 bytes to u64
> let mut bytes = [0u8; 8];
> bytes.copy_from_slice(&u_256[0..8]);
> Some(u64::from_le_bytes(bytes))
> }
> 
> ```

- I think bytes[0] is not a valid function is sway-lib-std

```auto
let b_256 = value.bytes[0];

```

but I can find this in sway-std-lib to convert B512 to bytes

```auto
let b_256 = value.bits()[0];

```

as mentioned [HERE](https://github.com/FuelLabs/sway/blob/5d796fb3c23bf9721985fc37fa835748086ba834/sway-lib-std/src/primitive_conversions/b256.sw)

- Also copy\_from\_slice() is is there in rust but I cannot find that function in sway

```auto
bytes.copy_from_slice(&u_256[0..8]);

```

---

<div class="post-metadata">

### Author: ![bitzoic](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/bitzoic/32/2077_2.png) [@bitzoic](https://forum.fuel.network/u/bitzoic)
#### Post date: [August 8, 2024, 4:22am UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/4 "2024-08-08T04:22:24Z")

</div>

This compiles for me on forc v0.61.2

```rust
fn b512_to_u64(b512: B512) -> Option<u64> {
    // Loss of precision
    if b512.bits()[0] != b256::zero() {
        return None;
    }

    // Extract the lower 256 bits from the B512 value
    let lower_u_256 = b512.bits()[1].as_u256();
    <u64 as TryFrom<u256>>::try_from(lower_u_256)
}

#[test]
fn convert() {
    let my_b512 = B512::zero();

    let my_u64 = b512_to_u64(my_b512);
    assert(my_u64.is_some());
}

```

---

<div class="post-metadata">

### Author: ![div-lync](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/div-lync/32/3441_2.png) [@div-lync](https://forum.fuel.network/u/div-lync)
#### Post date: [August 12, 2024, 11:16am UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/5 "2024-08-12T11:16:34Z")

</div>

```auto
 // Loss of precision
    if b512.bits()[0] != b256::zero() {
        return None;
    }

```

- Why do we need this ?

---

<div class="post-metadata">

### Author: ![div-lync](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/div-lync/32/3441_2.png) [@div-lync](https://forum.fuel.network/u/div-lync)
#### Post date: [August 13, 2024, 4:51am UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/6 "2024-08-13T04:51:41Z")

</div>

- I am trying to use this solution for converting the B512 random number I got from VRF to u64

```auto
Transaction Id(request): 0x18fe0a3ec7fe10f49e1aa78c0c9cc9258325a3a8258a8c361bc9b435f9c0e7de
random number (seed1): 0xed608a702150f07b52924bd7021358040c5e8d7925db8c31121e569b9892168cbd56a63638dc78eacabc1cf13f6afe8bb74f8e75623f2ae28f7118bb7a935d29
Number is undefined

```

- As u can see above , I cannot convert this random number to u64 using this code

```auto
fn convert(num :B512) -> Option<u64> {
        // Loss of precision
        if num.bits()[0] != b256::zero() {
            return None;
        }

        // Extract the lower 256 bits from the B512 value
        let lower_u_256 = num.bits()[1].as_u256();
        <u64 as TryFrom<u256>>::try_from(lower_u_256)
    }

```

```auto
const random_number :any= await contract.functions.get_random_number(seed1)
  .addContracts([Vrf])
  .get();
  console.log(`random number (seed1): ${random_number.value}`);

  const num = await contract.functions.convert(random_number.value).get();

  console.log("Number is ",num.value);

```

---

<div class="post-metadata">

### Author: ![bitzoic](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.fuel.network/bitzoic/32/2077_2.png) [@bitzoic](https://forum.fuel.network/u/bitzoic)
#### Post date: [August 16, 2024, 11:27pm UTC](https://forum.fuel.network/t/how-to-convert-b512-type-to-u64-type/6425/7 "2024-08-16T23:27:20Z")

</div>

You are trying to downsize a type with 512 bits to 64 bits. A `u64` cannot hold nearly as much data as a `B512` for this reason. As such you need to make sure you’ve not exceeded `u64::max()` by using any of the upper 256 bits with the `if` statement and the lower 256 bits are handled in the `TryFrom` statement.
