极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9837|回复: 1

贡献开源的位操作函数

[复制链接]
发表于 2012-9-22 18:09:15 | 显示全部楼层 |阅读模式
本帖最后由 test01 于 2012-10-13 02:46 编辑

[pre lang="C" line="1"]/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

uint64_t read_bit (uint64_t source_bits, uint_fast8_t source_width, uint_fast8_t n)  //Lowest order is 0
{
  const uint_fast8_t MAXIMUM_WIDTH_BIT = 64;
  
  if ((source_bits >> source_width) not_eq 0)
  {
    return source_bits;
  }
  if (source_width > MAXIMUM_WIDTH_BIT)
  {
    return source_bits;
  }
  if (n >= source_width)
  {
    return source_bits;
  }
  return (source_bits >> n) bitand ((uint64_t)0x01);
}

uint64_t write_bit (uint64_t source_bits, uint_fast8_t source_width, uint_fast8_t n, uint_fast8_t a_bit)  //Lowest order is 0
{
  const uint_fast8_t MAXIMUM_WIDTH_BIT = 64;
  
  if ((source_bits >> source_width) not_eq 0)
  {
    return source_bits;
  }
  if (source_width > MAXIMUM_WIDTH_BIT)
  {
    return source_bits;
  }
  if (n >= source_width)
  {
    return source_bits;
  }
  if ((a_bit >> 1) not_eq 0)
  {
    return source_bits;
  }
  (a_bit == 0) ? (source_bits and_eq (compl(((uint64_t)0x01) << n))) : (source_bits or_eq (((uint64_t)0x01) << n));
  return source_bits;
}

uint64_t xor_bit (uint64_t source_bits, uint_fast8_t source_width, uint_fast8_t n, uint_fast8_t a_bit)  //Lowest order is 0
{
  const uint_fast8_t MAXIMUM_WIDTH_BIT = 64;
  
  if ((source_bits >> source_width) not_eq 0)
  {
    return source_bits;
  }
  if (source_width > MAXIMUM_WIDTH_BIT)
  {
    return source_bits;
  }
  if (n >= source_width)
  {
    return source_bits;
  }
  if ((a_bit >> 1) not_eq 0)
  {
    return source_bits;
  }
  return source_bits xor (((uint64_t)a_bit) << n);
}[/code]
==========================
纯C11草案标准写的
加了输入参数范围检查
有什么使用问题欢迎留言
回复

使用道具 举报

 楼主| 发表于 2012-10-13 02:45:56 | 显示全部楼层
为更方便大家应用,变更了开源许可证
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-29 02:06 , Processed in 0.040047 second(s), 17 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表