【问题标题】:Best way to declare specific width variables depending on user input根据用户输入声明特定宽度变量的最佳方式
【发布时间】:2015-03-16 16:17:15
【问题描述】:

我有一个如下所示的代码。这里的代码是word_size = 64。以类似的方式,我也需要 32 和 16。我找不到为所有尺寸重用相同的encrypt 函数的方法。此外,我还需要根据word_size声明变量,即。使用 uint_16uint_32uint_64 取决于 word_size。在这种情况下,你能帮我写一个可重用的代码吗?

#include<stdio.h>
#include<stdint.h>

void encrypt(uint64_t* , uint64_t*, uint64_t*);

int main(){

    int block_size;

    // Get the user inputs
    printf("input the block size: \n");
    scanf("%d", &block_size);   // can be 32, 64 or 128

    int word_size = block_size/2;   // 16,32 or 64

    // Depending on the word_size, I should declare the variables with 
    // corresponding width
    uint64_t plain_text[2] = {0,0};  
    uint64_t cipher_text[2] = {0,0}; 
    uint64_t key_text[2] = {0,0};   

    uint64_t * pt, *ct, *k;
    encrypt(pt, ct,k);
    }

 /*
 * Ecnryption Method
 */
void encrypt(uint64_t* pt, uint64_t* ct, uint64_t* k){

    // Involves bit shifting algorithm which works only on exact sizes i.e eiter 16,32 or 64.
        }

如果需要,我可以提供更多信息。

【问题讨论】:

  • 定义最大尺寸的函数,并使其接受额外的宽度参数。然后通过将输入与每种类型的最大值进行比较来确定运行时的宽度。
  • 您可以选择使用 C++ 吗?如果你这样做了,那么函数模板将解决你的设计问题。
  • 抱歉没有 C++ 选项。在 C 语言中没有简单的方法吗?
  • @EugeneSh。按照你所说的,如果我传递一个较小的值,那么它会在 MSB 上填充 0 以使其成为 64 位,对吗?如果是这种情况,该函数将无法执行算法。
  • 这就是为什么要传递宽度参数。您的算法应该查看它并自行调整。

标签: c reusability stdint


【解决方案1】:

在 C 中有一种方法可以做到这一点 - 使用 structunion

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>

enum type {
    U64,
    U32,
    U16,
    U8,
};
struct container {
    enum type type;
    union {
        uint64_t u64;
        uint32_t u32;
        uint16_t u16;
        uint8_t  u8;
    } value;
};

int test(struct container container) {
    switch(container.type) {
        case U64:
            printf("Value is  :%" PRIu64 "\n", container.value);
            break;
        case U32:
            printf("Value is  :%" PRIu32 "\n", container.value);
            break;
        case U16:
            printf("Value is  :%" PRIu16 "\n", container.value);
            break;
        case U8:
            printf("Value is  :%" PRIu8 "\n", container.value);
            break;
    }
    return 0;
}

int main(int argc, char **argv) {
    struct container c1, c2;

    c1.type = U64;
    c1.value.u64 = 10000000000ULL;

    c2.type = U8;
    c2.value.u8 = 100;

    test(c1);
    test(c2);
    return 0;
}

产生的输出是:

Value is  :10000000000
Value is  :100

【讨论】:

  • 如果您希望我尝试用您的代码而不是我使用的示例代码为您提供示例,请告诉我。
  • 您可能还需要定义不同的位掩码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多