Next higher number with same number of set bits

寻找下一个更高数
本文介绍了一种高效算法,用于找到给定整数下一个具有相同数量1位的更高整数。通过巧妙地操作二进制位,该算法展示了如何实现这一目标,并提供了详细的步骤解释和示例。

reference: 

http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/


Problem Definition:

Given a number x, find next number with same number of 1 bits in it’s binary representation.

For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).


Solution:

When we observe the binary sequence from 0 to 2n – 1 (n is # of bits), right most bits (least significant) vary rapidly than left most bits. The idea is to find right most string of 1′s in x, and shift the pattern to right extreme, except the left most bit in the pattern. Shift the left most bit in the pattern (omitted bit) to left part of x by one position. An example makes it more clear,

x = 156

10

x = 10011100

(2)

10011100
00011100 - right most string of 1's in x
00000011 - right shifted pattern except left most bit ------> [A]
00010000 - isolated left most bit of right most 1's pattern
00100000 - shiftleft-ed the isolated bit by one position ------> [B]
10000000 - left part of x, excluding right most 1's pattern ------> [C]
10100000 - add B and C (OR operation) ------> [D]
10100011 - add A and D which is required number 163

(10)

After practicing with few examples, it easy to understand. Use the below given program for generating more sets.

Program Design:

We need to note few facts of binary numbers. The expression x & -x will isolate right most set bit in x (ensuring x will use 2′s complement form for negative numbers). If we add the result to x, right most string of 1′s in x will be reset, and the immediate ’0′ left to this pattern of 1′s will be set, which is part [B] of above explanation. For example if x = 156, x & -x will result in 00000100, adding this result to x yields 10100000 (see part D). We left with the right shifting part of pattern of 1′s (part A of above explanation).

There are different ways to achieve part A. Right shifting is essentially a division operation. What should be our divisor? Clearly, it should be multiple of 2 (avoids 0.5 error in right shifting), and it should shift the right most 1′s pattern to right extreme. The expression (x & -x) will serve the purpose of divisor. An EX-OR operation between the number X and expression which is used to reset right most bits, will isolate the rightmost 1′s pattern.

A Correction Factor:

Note that we are adding right most set bit to the bit pattern. The addition operation causes a shift in the bit positions. The weight of binary system is 2, one shift causes an increase by a factor of 2. Since the increased number (rightOnesPattern in the code) being used twice, the error propagates twice. The error needs to be corrected. A right shift by 2 positions will correct the result.

The popular name for this program is same number oone bits.

Usage: Finding/Generating subsets.


Code:

typedef unsigned int uint_t;
 
// this function returns next higher number with same number of set bits as x.
uint_t snoob(uint_t x)
{
 
  uint_t rightOne;
  uint_t nextHigherOneBit;
  uint_t rightOnesPattern;
 
  uint_t next = 0;
 
  if(x)
  {
 
    // right most set bit
    rightOne = x & -(signed)x;
 
    // reset the pattern and set next higher bit
    // left part of x will be here
    nextHigherOneBit = x + rightOne;
 
    // nextHigherOneBit is now part [D] of the above explanation.
 
    // isolate the pattern
    rightOnesPattern = x ^ nextHigherOneBit;
 
    // right adjust pattern
    rightOnesPattern = (rightOnesPattern)/rightOne;
 
    // correction factor
    rightOnesPattern >>= 2;
 
    // rightOnesPattern is now part [A] of the above explanation.
 
    // integrate new pattern (Add [D] and [A])
    next = nextHigherOneBit | rightOnesPattern;
  }
 
  return next;
}


Enhanced sFlow This section is applicable for the following families of devices: a Falcon a AlleyCat5P a AlleyCat5X At times, it is useful for the controller to obtain the original packet’s input/output port and the Ingress/Egress timestamp. The controller can then utilize this information to calculate message forwarding delay, and draw the forwarding delay jitter curve, thus provide information on network transmission quality. For that purpose, enhanced sFlow packet format is defined. Enhanced sFlow format is a proprietary format based on standard sFlow v5. Enhanced sFlow tunnel Layer4 encapsulation can be either: IPv4/UDP IPv6/UDP Enhanced sFlow Architecture Due to Falcon HW, the enhanced sFlow solution requires one free loopback port through which the mirrored traffic is looped back to the device. The following figure illustrates the engaged components, and is followed by a description of data flow. Figure 179: Enhanced sFlow Components and Data Flow The first path (light-blue arrows): Egress mirroring is enabled on Sample port X by EPCL. An EPCL rule matches the packet, assigns it any of the target analyzer IDs (1-7), and triggers a PHA thread to save target information into the copy-reserved descriptor field. The Egress Replication Engine (EREP) duplicates packet descriptor, and assigns the mirrored packet to the target analyzer ID configured by EPCL. Then, the pre-Egress engine (EQ) maps the target analyzer ID to Analyzer port (loopback port Y). A second EPCL rule matches the mirrored packet, and binds it to a second PHA thread. This second PHA thread adds an sFlow header prefixing the mirrored packet; this header incorporate most of the header fields except those of the tunnel header. PTP TSU (TimeStamping Unit) adds a Tx timestamp to the sFlow header. Port Y is set as a loopback port. The second path (blue arrows): Once packet is looped back to pipeline, a Private VLAN Edge (PVE), or an IPCL rule, matches the looped back traffic, and assigns a target ePort with a Tunnel start attribute. The ePort to Physical port (E2PHY) maps the target ePort to an output port, from which it is streamed to a Collector unit. A third EPCL rule matches the looped back traffic, and binds it to a third PHA thread, which sets the tunnel start field in the sFlow header. CPSS Implementation Considerations The application is responsible for setting the following CPSS parameters: Sampling Port, formatted as dev_id/port_num, and sampling rate 1:N Target analyzer ID: ranged 1-7 Target ePort number for Tunnel start Analyzer port number – loopback port Y in illustration Tunnel Start (TS) entry pointer Physical Analyzer port, formatted as dev_id/port_num, connected to the Collector unit – output port A in illustration Analyzer Node IP address – 32bits representing dev_id, and used for setting IP_High and IP_Low fields In addition, the application needs to configure the following components: Table 113: Component Configuration by Application Component Configuration per Steps Mirror engine Set MIRROR to analyzer port Set ratio to 1:N rate Set analyzed ePort to loopback port Y ePort for Tunnel start Set target ePort with tunnel start attributes; for example, UDP over IPv4 Tunnel Implement 2 tunnel configuration APIs—DMAC, SMAC, DIP, SIP, Dport, and Sport API for setting Tunnel Start entry pointer parameter A call of type <customer-prefix>sflowTunnelStartSet (TSentry* TSentryPointer) API for setting tunnel configuration, and mapping target ePort to an output port A connected to a collector unit; pass DMAC, SMAC, DIP, SIP, Dport, and Sport as parameter A call of type EtoPHY Assign tunnel start ePort to looped back traffic by one of two methods Method 1: Use PVE Enable PVE Set Bridge Global configuration0 register to <PVLAN Enable> (bit 14 in register) Enable ePort for PVE Set Ingress bridge ePort for loopback port Y to <PortPVLANEn> Set destination port for the set PVE port Y Set physical Analyzer output port A connected to collector unit at the Ingress bridge ePort table to <PortPVLANTrgEport>/ <PortPVLANTrgDev> Method2: Use an IPCL rule Match looped back traffic, and assign the collector unit ePort. This ePort attribute acts as tunnel start, with: Key: UDB Metadata <source port > = loopback port Y Packet first word (32bit) = 0x5 (sflow version) Action: <redirect command> = target Egress interface Target egress interface = ePort (output port A connected to collector) EPCL rules First EPCL rule Enable Egress mirroring, and trigger the first PHA thread THR61_save_target_port_info with: Key: UDB Metadata <source port> = sample port Action: <Egress Mirror to Analyzer> = Target analyzer ID //binds to an analyzer ID assigned by User <Egress Mirror mode> = Egress Mirror packet not DROPPED <PHA Thread Number Assignment Enable> = 1 <PHA Thread number> = THR61_save_target_port_info Second EPCL rule NOTE: The second EPCL rule priority must be higher than that of the first one Match mirrored traffic, and trigger the second PHA thread THR66_enhanced_sFlow Key: UDB Metadata <Egress Mtag Cmd> = TO_ANALYZER UDB Metadata <Analyzer Target ePort> = Analyzer port number (loopback port Y) Action: Disable OAM engine by <OAM Processing En> = 0. PHA counts Packet number with flow ID as index Use analyzer ID as flow index by <Flow-ID> = Target analyzer ID. Flow index is used by second PHA thread THR66_enhanced_sFlow <PHA Thread Number Assignment Enable> = 1 <PHA Thread number> = THR66_enhanced_sFlow Third EPCL rule Match looped back traffic, and trigger third PHA thread THR62_enhanced_sFlow_fill_remain_IPv4 or THR63_enhanced_sFlow_fill_remain_IPv6 Key: UDB Metadata <source port> = loopback port Y Action: <PHA Thread Number Assignment Enable> = 1 <PHA Thread number> = THR62_enhanced_sFlow_fill_remain_IPv4 or THR63_enhanced_sFlow_fill_remain_IPv6 <PHA metadata assignment enable> = True Pass node IP address to PHA to enable adding of sflow header by third PHA thread <metadata[31:0]> = Analyzer Node IP address[31:0] PHA Firmware Description First PHA thread – THR61_save_target_port_info Save target port information into the copy reserved field. Second PHA thread – THR66_enhanced_sFlow FW adds sFlow header. Since TS is moved to the next path after the loopback, currently no need to split for ipv4/ipv6. Third PHA thread – THR62_enhanced_sFlow_fill_remain_IPv4 or THR63_enhanced_sFlow_fill_remain_IPv6 FW adds remainder of sFlow field relative to tunnel start. Since TS uses IPv4/IPv6 encapsulation, this thread is split into IPv4 and IPv6. Table 114: PHA Thread Implementation by Application Thread Steps THR61_save_target_port_info Save target port information into the copy reserved field THR66_enhanced_sFlow Insert sFlow header before the mirrored packet Set sFlow header Enable PTP TSU THR62_enhanced_sFlow_fill_remain_IPv4 After loopback, traffic reenters pipeline, and Tunnel Start wraps sFlow header with IPv4 encapsulation. sFlow header offset is 44 bytes: L3 anchor + 20 Bytes for IP header + 8 Bytes for UDP header Update UDP and IP length and checksum THR63_enhanced_sFlow_fill_remain_IPv6 Same as IPv4 except Tunnel Start uses IPv6 encapsulation sFlow header offset changes according to IPv6 Update UDP and checksum 该过程IPCL和EPCL优先级有什么要求
10-10
在充满仪式感的生活里,一款能传递心意的小工具总能带来意外惊喜。这款基于Java开发的满屏飘字弹幕工具,正是为热爱生活、乐于分享的你而来——它以简洁优雅的视觉效果,将治愈系文字化作灵动弹幕,在屏幕上缓缓流淌,既可以作为送给心仪之人的浪漫彩蛋,也能成为日常自娱自乐、舒缓心情的小确幸。 作为程序员献给crush的心意之作,工具的设计藏满了细节巧思。开发者基于Swing框架构建图形界面,实现了无边框全屏显示效果,搭配毛玻璃质感的弹幕窗口与圆润边角设计,让文字呈现既柔和又不突兀。弹幕内容精选了30条治愈系文案,从“秋天的风很温柔”到“你值得所有温柔”,涵盖生活感悟、自我关怀、浪漫告白等多个维度,每一条都能传递温暖力量;同时支持自定义修改文案库,你可以替换成专属情话、纪念文字或趣味梗,让弹幕更具个性化。 在视觉体验上,工具采用柔和色调生成算法,每一条弹幕都拥有独特的清新配色,搭配半透明渐变效果与平滑的移动动画,既不会遮挡屏幕内容,又能营造出灵动治愈的氛围。开发者还优化了弹幕的生成逻辑,支持自定义窗口大小、移动速度、生成间隔等参数,最多可同时显示60条弹幕,且不会造成电脑卡顿;按下任意按键即可快速关闭程序,操作便捷无负担。 对于Java学习者而言,这款工具更是一份优质的实战参考。源码完整展示了Swing图形界面开发、定时器调度、动画绘制、颜色算法等核心技术,注释清晰、结构简洁,哪怕是初学者也能轻松理解。开发者在AI辅助的基础上,反复调试优化细节,解决了透明度控制、弹幕碰撞、资源占用等多个问题,这份“踩坑实录”也为同类项目开发提供了宝贵经验。 无论是想给喜欢的人制造浪漫惊喜,用满屏文字传递心意;还是想在工作间隙用治愈文案舒缓压力,或是作为Java学习的实战案例参考,这款满屏飘字弹幕工具都能满足你的需求。它没有复杂的操作流程,无需额外配置环境,下载即可运行,用最纯粹的设计传递最真挚的
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值