How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?










1















I want to convert a u16 to two separate u8s. I tried to use some bit masks:



use std::convert::From;

fn main()
let n1: u8 = 0x41;
let n2: u16 = 0x4157;

println!("Number:", char::from(n1));

let b1: u8 = n2 & 0xFF;
let b2: u8 = n2 >> 8;

println!("b1: ", b1);
println!("b2: ", b2);



error[E0308]: mismatched types
--> src/main.rs:9:18
|
9 | let b1: u8 = n2 & 0xFF;
| ^^^^^^^^^ expected u8, found u16

error[E0308]: mismatched types
--> src/main.rs:10:18
|
10 | let b2: u8 = n2 >> 8;
| ^^^^^^^ expected u8, found u16


This question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.










share|improve this question
























  • Reference

    – jhpratt
    Nov 15 '18 at 7:15











  • Possible duplicate of How to idiomatically convert between u32 and usize?

    – E_net4
    Nov 15 '18 at 9:52











  • @E_net4 not really I'm afraid

    – hellow
    Nov 15 '18 at 11:07











  • @hellow Quoting from the accepted answer: "The as operator works for all number types [...] Rust forces you to cast integers to make sure you're aware of signedness or overflows." Therefore, it pretty much answers why the compiler raises a mismatched types error.

    – E_net4
    Nov 15 '18 at 11:14











  • @E_net4 I would argue otherwise because the actual question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

    – the_endian
    Nov 15 '18 at 16:50
















1















I want to convert a u16 to two separate u8s. I tried to use some bit masks:



use std::convert::From;

fn main()
let n1: u8 = 0x41;
let n2: u16 = 0x4157;

println!("Number:", char::from(n1));

let b1: u8 = n2 & 0xFF;
let b2: u8 = n2 >> 8;

println!("b1: ", b1);
println!("b2: ", b2);



error[E0308]: mismatched types
--> src/main.rs:9:18
|
9 | let b1: u8 = n2 & 0xFF;
| ^^^^^^^^^ expected u8, found u16

error[E0308]: mismatched types
--> src/main.rs:10:18
|
10 | let b2: u8 = n2 >> 8;
| ^^^^^^^ expected u8, found u16


This question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.










share|improve this question
























  • Reference

    – jhpratt
    Nov 15 '18 at 7:15











  • Possible duplicate of How to idiomatically convert between u32 and usize?

    – E_net4
    Nov 15 '18 at 9:52











  • @E_net4 not really I'm afraid

    – hellow
    Nov 15 '18 at 11:07











  • @hellow Quoting from the accepted answer: "The as operator works for all number types [...] Rust forces you to cast integers to make sure you're aware of signedness or overflows." Therefore, it pretty much answers why the compiler raises a mismatched types error.

    – E_net4
    Nov 15 '18 at 11:14











  • @E_net4 I would argue otherwise because the actual question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

    – the_endian
    Nov 15 '18 at 16:50














1












1








1








I want to convert a u16 to two separate u8s. I tried to use some bit masks:



use std::convert::From;

fn main()
let n1: u8 = 0x41;
let n2: u16 = 0x4157;

println!("Number:", char::from(n1));

let b1: u8 = n2 & 0xFF;
let b2: u8 = n2 >> 8;

println!("b1: ", b1);
println!("b2: ", b2);



error[E0308]: mismatched types
--> src/main.rs:9:18
|
9 | let b1: u8 = n2 & 0xFF;
| ^^^^^^^^^ expected u8, found u16

error[E0308]: mismatched types
--> src/main.rs:10:18
|
10 | let b2: u8 = n2 >> 8;
| ^^^^^^^ expected u8, found u16


This question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.










share|improve this question
















I want to convert a u16 to two separate u8s. I tried to use some bit masks:



use std::convert::From;

fn main()
let n1: u8 = 0x41;
let n2: u16 = 0x4157;

println!("Number:", char::from(n1));

let b1: u8 = n2 & 0xFF;
let b2: u8 = n2 >> 8;

println!("b1: ", b1);
println!("b2: ", b2);



error[E0308]: mismatched types
--> src/main.rs:9:18
|
9 | let b1: u8 = n2 & 0xFF;
| ^^^^^^^^^ expected u8, found u16

error[E0308]: mismatched types
--> src/main.rs:10:18
|
10 | let b2: u8 = n2 >> 8;
| ^^^^^^^ expected u8, found u16


This question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.







rust bit-manipulation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 17:03







the_endian

















asked Nov 15 '18 at 6:59









the_endianthe_endian

567622




567622












  • Reference

    – jhpratt
    Nov 15 '18 at 7:15











  • Possible duplicate of How to idiomatically convert between u32 and usize?

    – E_net4
    Nov 15 '18 at 9:52











  • @E_net4 not really I'm afraid

    – hellow
    Nov 15 '18 at 11:07











  • @hellow Quoting from the accepted answer: "The as operator works for all number types [...] Rust forces you to cast integers to make sure you're aware of signedness or overflows." Therefore, it pretty much answers why the compiler raises a mismatched types error.

    – E_net4
    Nov 15 '18 at 11:14











  • @E_net4 I would argue otherwise because the actual question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

    – the_endian
    Nov 15 '18 at 16:50


















  • Reference

    – jhpratt
    Nov 15 '18 at 7:15











  • Possible duplicate of How to idiomatically convert between u32 and usize?

    – E_net4
    Nov 15 '18 at 9:52











  • @E_net4 not really I'm afraid

    – hellow
    Nov 15 '18 at 11:07











  • @hellow Quoting from the accepted answer: "The as operator works for all number types [...] Rust forces you to cast integers to make sure you're aware of signedness or overflows." Therefore, it pretty much answers why the compiler raises a mismatched types error.

    – E_net4
    Nov 15 '18 at 11:14











  • @E_net4 I would argue otherwise because the actual question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

    – the_endian
    Nov 15 '18 at 16:50

















Reference

– jhpratt
Nov 15 '18 at 7:15





Reference

– jhpratt
Nov 15 '18 at 7:15













Possible duplicate of How to idiomatically convert between u32 and usize?

– E_net4
Nov 15 '18 at 9:52





Possible duplicate of How to idiomatically convert between u32 and usize?

– E_net4
Nov 15 '18 at 9:52













@E_net4 not really I'm afraid

– hellow
Nov 15 '18 at 11:07





@E_net4 not really I'm afraid

– hellow
Nov 15 '18 at 11:07













@hellow Quoting from the accepted answer: "The as operator works for all number types [...] Rust forces you to cast integers to make sure you're aware of signedness or overflows." Therefore, it pretty much answers why the compiler raises a mismatched types error.

– E_net4
Nov 15 '18 at 11:14





@hellow Quoting from the accepted answer: "The as operator works for all number types [...] Rust forces you to cast integers to make sure you're aware of signedness or overflows." Therefore, it pretty much answers why the compiler raises a mismatched types error.

– E_net4
Nov 15 '18 at 11:14













@E_net4 I would argue otherwise because the actual question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

– the_endian
Nov 15 '18 at 16:50






@E_net4 I would argue otherwise because the actual question is not why does the compiler raise a mismatched type error?, rather, it is How can I convert the lower/upper 8 bits of a u16 to a u8 in Rust?. Potentially, there are other ways to do this and this question does not constrain the answer to the as keyword.

– the_endian
Nov 15 '18 at 16:50













2 Answers
2






active

oldest

votes


















3














You can use the as keyword to convert a u16 to u8 in a safe way.



fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] 
[(integer >> 8) as u8, integer as u8]



If you need more types or different endianness use the byteorder crate.



extern crate byteorder;

use byteorder::WriteBytesExt, BigEndian;

fn convert_u16_to_two_u8s_be(integer: u16) -> Vec<u8>
let mut res = vec!;
res.write_u16::<BigEndian>(integer).unwrap();
res






share|improve this answer
































    3














    You can cast between integer types with as.



    let b1 = n2 as u8;
    let b2 = (n2 >> 8) as u8;


    Note that the masking is unnecessary, because the cast will truncate the upper bits.






    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53314005%2fhow-can-i-convert-the-lower-upper-8-bits-of-a-u16-to-a-u8-in-rust%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      You can use the as keyword to convert a u16 to u8 in a safe way.



      fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] 
      [(integer >> 8) as u8, integer as u8]



      If you need more types or different endianness use the byteorder crate.



      extern crate byteorder;

      use byteorder::WriteBytesExt, BigEndian;

      fn convert_u16_to_two_u8s_be(integer: u16) -> Vec<u8>
      let mut res = vec!;
      res.write_u16::<BigEndian>(integer).unwrap();
      res






      share|improve this answer





























        3














        You can use the as keyword to convert a u16 to u8 in a safe way.



        fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] 
        [(integer >> 8) as u8, integer as u8]



        If you need more types or different endianness use the byteorder crate.



        extern crate byteorder;

        use byteorder::WriteBytesExt, BigEndian;

        fn convert_u16_to_two_u8s_be(integer: u16) -> Vec<u8>
        let mut res = vec!;
        res.write_u16::<BigEndian>(integer).unwrap();
        res






        share|improve this answer



























          3












          3








          3







          You can use the as keyword to convert a u16 to u8 in a safe way.



          fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] 
          [(integer >> 8) as u8, integer as u8]



          If you need more types or different endianness use the byteorder crate.



          extern crate byteorder;

          use byteorder::WriteBytesExt, BigEndian;

          fn convert_u16_to_two_u8s_be(integer: u16) -> Vec<u8>
          let mut res = vec!;
          res.write_u16::<BigEndian>(integer).unwrap();
          res






          share|improve this answer















          You can use the as keyword to convert a u16 to u8 in a safe way.



          fn convert_u16_to_two_u8s_be(integer: u16) -> [u8; 2] 
          [(integer >> 8) as u8, integer as u8]



          If you need more types or different endianness use the byteorder crate.



          extern crate byteorder;

          use byteorder::WriteBytesExt, BigEndian;

          fn convert_u16_to_two_u8s_be(integer: u16) -> Vec<u8>
          let mut res = vec!;
          res.write_u16::<BigEndian>(integer).unwrap();
          res







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 15 '18 at 15:59









          Shepmaster

          157k14316457




          157k14316457










          answered Nov 15 '18 at 7:31









          hellowhellow

          5,34242242




          5,34242242























              3














              You can cast between integer types with as.



              let b1 = n2 as u8;
              let b2 = (n2 >> 8) as u8;


              Note that the masking is unnecessary, because the cast will truncate the upper bits.






              share|improve this answer



























                3














                You can cast between integer types with as.



                let b1 = n2 as u8;
                let b2 = (n2 >> 8) as u8;


                Note that the masking is unnecessary, because the cast will truncate the upper bits.






                share|improve this answer

























                  3












                  3








                  3







                  You can cast between integer types with as.



                  let b1 = n2 as u8;
                  let b2 = (n2 >> 8) as u8;


                  Note that the masking is unnecessary, because the cast will truncate the upper bits.






                  share|improve this answer













                  You can cast between integer types with as.



                  let b1 = n2 as u8;
                  let b2 = (n2 >> 8) as u8;


                  Note that the masking is unnecessary, because the cast will truncate the upper bits.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 7:31









                  Benjamin LindleyBenjamin Lindley

                  86.3k4138230




                  86.3k4138230



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53314005%2fhow-can-i-convert-the-lower-upper-8-bits-of-a-u16-to-a-u8-in-rust%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      How to read a connectionString WITH PROVIDER in .NET Core?

                      In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                      Museum of Modern and Contemporary Art of Trento and Rovereto