Equivalent of JavaScript's toString(16) in iOS using Obj-C

My goal is to create a unique hex id string using a random number. I accomplish this in JavaScript with the following code:

var id = (
    Math.random() * Math.pow(10, 17) +
    Math.random() * Math.pow(10, 17) +
    Math.random() * Math.pow(10, 17) +
    Math.random() * Math.pow(10, 17)
).toString(16);

This results in a random id such as: "2d50e9b4835d7e0".

I am now looking for a similar method in iOS that can generate a string of the same length (15 characters). Does anyone know of an iOS function that can achieve this?

Answer №1

To generate a random number in Objective C, you can use the following code snippet:

-(int)getRandomNumberBetween:(int)from to:(int)to {
    return (int)from + arc4random() % (to-from+1);
}

Update: I have made changes to this method in order to obtain a hexadecimal string.

- (NSString *)getHexString
{   
    NSString *longString = [NSString stringWithFormat:@"%d%d%d%d%d%d",[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999],[self getRandomNumberBetween:100 to:999]];
    long long longNumber = [longString longLongValue];
    NSString *hexadecimalStr =  [NSString stringWithFormat:@"%llx",longNumber];
    NSLog(@"%@",hexadecimalStr);
     return hexadecimalStr;
}

Therefore, your code will now resemble the following:

NSString *hexadecimalStr = [self getHexString];

You can customize it based on your requirements, as it provides a 15-digit hexadecimal value.

Answer №2

After some investigation, I managed to figure out how to solve this problem:

#define customPow pow(3, 19)

long long value = ((
    rand() * customPow +
    rand() * customPow +
    rand() * customPow +
    rand() * customPow
));

NSString *uniqueId = [[NSString alloc] initWithFormat:@"%llx", value];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to convert a single object into an array of multiple objects?

Is there a way to convert this into an array of objects that are ordered based on another array's keys? { tom: 11, jim: 22, jay: 13 } Here are some input -> output examples: ['jim', 'tom', 'kim', 'jay&apo ...

What is the best technique to incorporate dark/light mode in Bootstrap 5?

Is it best to introduce themes such as dark and light themes in Bootstrap 5 using CSS/SCSS, JavaScript, or a combination of both? Should we create a separate CSS file like dark.css to overwrite classes? Or should we use JavaScript to switch classes like ...

Multiple presentations displayed on a single webpage

I have searched through various threads with similar questions, but I cannot seem to find information that is relevant to the functions I am working with. My issue lies with creating an automatic slideshow using HTML, CSS, and JS. While it works perfectly ...

Why does this image slider begin with blankness?

For my recent school project, I created an image slider. However, upon starting the page or reloading it, only the arrows and dots are displayed. View screenshot of the issue Below is the code snippet: // JavaScript function to control the slideshow sho ...

Aligning the Bootstrap 5 navbar dropdown to the right side

I'm having trouble getting a part of my navbar to align right in bootstrap 5. I've followed the new documentation, but I think I might be adding the text in the wrong place. Can someone assist me in moving my dropdown to the right side of the nav ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

Enhancing images with JCrop's height and width adjustments

I am currently utilizing JCrop for photo cropping, and I have encountered an issue where the image clicked on is not displaying at the set width and height. Instead, it appears smaller when loaded in a modal window. Here is an example of the code snippet: ...

What could be causing the unexpected behavior in my NgMessages form validation?

I have developed a code that incorporates Angular JS form validation methods. There are two separate forms within the codebase, The initial form utilizes basic form validation while the second form employs ng-messages, However, an issue has arisen wher ...

Encasing the window global variable within an AngularJS framework

Currently, I am encapsulating a global variable within a factory in order to make it injectable. Here is an example of how it's done: angular.module('Analytics').factory('woopra', [ '$window', function ($window) ...

What am I doing wrong in my Javascript or jQuery code that is causing me to constantly receive

I am facing an issue with the following HTML code snippet: <a class="tabTitle" id="title_boxtab_default" tab-type="default" href="#tabs-3">Sample</a> When using jQuery, I am attempting to retrieve the value of the href attribute using the fol ...

Is there a way to call a method from a different View Controller in Swift without using push segues?

I have a scenario with two View Controllers, Vc1 and Vc2. The navigation from Vc1 to Vc2 is done using the code snippet below: let vc2 = Vc2(nibName: "Vc2", bundle: nil) self.navigationController?.pushViewController(vc2, animated: true) Then in Vc2, I ...

Is there a way to disregard the data returned from previous AJAX calls?

I've been wondering about a strategy for managing delayed AJAX data returns in a scenario where newer calls should take precedence over earlier ones. For instance, if a first data fetch initiated at 12:01:33 is delayed and comes back at 12:01;39, whil ...

"Troubleshooting: Sub-routes in AngularJS not displaying when directly typing in the

My AngularJS setup is configured to use HTML5 routes and it functions perfectly on urls like website.com/foo. However, I am facing an issue when creating routes for subpages, such as website.com/foo/bar. In this case, the correct page only appears when c ...

Can I Select a Specific Node in React Component with Unique Behavior Upon Reuse?

Seeking advice on how to uniquely target a specific node within my react reusable component in order to perform operations on it multiple times independently. I will be rendering this reusable component several times on the same page in my App.js. Here is ...

Provide the scope to the directive when calling the $uibModal.open method

I am interested in developing a custom directive that displays data based on the scope of its parent controller. Here is the directive's JavaScript code: (function () { 'use strict'; angular .module('blabla') ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

What could be the reason behind the failure of JSON.stringify() on this particular array?

I am encountering an issue with an array that I have declared like this: array = []; The array contains values that look like this - .... ChIJOaegwbTHwoARg7zN_9nq5Uc:"ChIJOaegwbTHwoARg7zN_9nq5Uc" ChIJXTwCdefHwoAR9Jr4-le12q4:"ChIJXTwCdefHwoAR9Jr4-le12q4 ...

The dimension of the window is not being properly updated in the resize handler within WKWebView

My fullscreen web content is supposed to update when the window size changes by using the resize event. window.onresize = function() { var width = window.innerWidth; var height = window.innerHeight; ... } While this functionality works as exp ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

Invoke the bootstrap js collapse() method within an Angular/Typescript environment

Currently, I am utilizing Bootstrap 3 alongside Angular 2 to collapse/hide content. However, I am facing an issue where I need the ability to collapse it when double-clicking on the button. Even though I created a function for this purpose, I seem to be un ...