简体   繁体   English

如何将一个 16 位数字分解为两个 8 位数字?

[英]How to decompose one 16bit number to two 8bit numbers?

I have this piece of code in C and I want in nasm, decompose the 16bit to two 8bits, How Can I do it?我在 C 中有这段代码,我想在 nasm 中,将 16 位分解为两个 8 位,我该怎么做? C C

uint16_t data = 0xCAFE; // global
uint8_t result[2];
...

decompose();
printf(
  "result %d %d \n", 
  result[0], result[1]
);

ASM ASM

 global decompose
decompose:
  enter 0,0
  movzx ax, word[data],
  movzx al, [ax]
  leave
  ret

first: it is very bad design to create functions that have global side effects eg get their arguments or pass their results via globals.首先:创建具有全局副作用的函数是非常糟糕的设计,例如获取它们的 arguments 或通过全局传递它们的结果。
second: there is absolutely no reason to use assembly on this.第二:绝对没有理由对此使用汇编。 especially not if you pass the result to comparable slow printing routines.如果您将结果传递给类似的慢速打印程序,尤其如此。

If you really want to have functions for that I would suggest to introduce small inline functions如果你真的想拥有这样的功能,我建议引入小的内联函数

static inline uint8_t u16High(uint16_t v){ return (uint8_t)(v >> 8); }
static inline uint8_t u16Low (uint16_t v){ return (uint8_t)(v);      }

Another (in my eyes ugly) option would be:另一个(在我看来丑陋的)选择是:

static inline uint8_t* u16decompose(uint16_t* v){ return (uint8_t*)v; }

But beware: this only is allowed for uint8_t* you may not use this for 'decompose' uint32_t into uint16_t because this violates the strict aliasing rule.但请注意:这仅允许用于uint8_t*您不能将其用于将uint32_t分解为uint16_t ,因为这违反了严格的别名规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM